package product_repository

import (
	_const "chonho/const"
	"chonho/internal/api-v1/entity"
	"encoding/json"
)

func (r *repository) FindProduct(filter ProductFilter) ([]entity.ProductItem, error) {
	var result []entity.ProductItem
	builder := r.db.Table("store_products sp").
		Select(`
			p.id,
			p.name, 
			p.description, 
			p.thumbnail, 
			p.images, 
			p.unit, 
			p.is_quote_after_ordering, 
			sp.stock, 
			sp.price, 
			sp.delivery_type, 
			sp.delivery_commit_time, 
			sp.store_id, 
			p.user_id AS seller_id, 
			p.category_id, 
			s.apartment_id
		`).
		Joins("JOIN stores s ON s.id = sp.store_id").
		Joins("JOIN products p ON p.id = sp.product_id")

	if filter.ProductId != 0 {
		builder.Where("p.id = ?", filter.ProductId)
	}

	if filter.SellerId != 0 {
		builder.Where("p.user_id = ?", filter.SellerId)
	}

	if filter.StoreId != 0 {
		builder.Where("sp.store_id = ?", filter.StoreId)
	}

	if filter.CategoryId != 0 {
		builder.Where("p.category_id = ?", filter.CategoryId)
	}

	if filter.ApartmentId != 0 {
		builder.Where("s.apartment_id = ?", filter.ApartmentId)
	}

	if filter.IgnoreDeleted {
		builder.Where("p.status != ?", _const.ProductStatusDeleted)
	}

	err := builder.Find(&result).Error
	if err != nil {
		return nil, err
	}

	for i, e := range result {
		var images []string
		err = json.Unmarshal([]byte(e.Images), &images)
		result[i].ImagesArray = images
	}
	return result, nil
}
