package repository

import (
	"jaecoo-be/app/database"
	"jaecoo-be/app/database/entity"
	"jaecoo-be/app/module/products/request"
	"jaecoo-be/utils/paginator"
	"strings"

	"github.com/rs/zerolog"
)

type productsRepository struct {
	DB  *database.Database
	Log zerolog.Logger
}

type ProductsRepository interface {
	GetAll(req request.ProductsQueryRequest) (products []*entity.Products, paging paginator.Pagination, err error)
	FindOne(id uint) (product *entity.Products, err error)
	Create(product *entity.Products) (productReturn *entity.Products, err error)
	Update(id uint, product *entity.Products) (err error)
	Delete(id uint) (err error)
	FindByThumbnailPath(thumbnailPath string) (product *entity.Products, err error)
}

func NewProductsRepository(db *database.Database, log zerolog.Logger) ProductsRepository {
	return &productsRepository{
		DB:  db,
		Log: log,
	}
}

func (_i *productsRepository) GetAll(req request.ProductsQueryRequest) (products []*entity.Products, paging paginator.Pagination, err error) {
	var count int64

	query := _i.DB.DB.Model(&entity.Products{})

	if req.Title != nil && *req.Title != "" {
		title := strings.ToLower(*req.Title)
		query = query.Where("LOWER(title) LIKE ?", "%"+title+"%")
	}

	if req.Variant != nil && *req.Variant != "" {
		query = query.Where("variant = ?", *req.Variant)
	}

	query = query.Where("is_active = ?", true)

	query.Count(&count)

	req.Pagination.Count = count
	req.Pagination = paginator.Paging(req.Pagination)

	query = query.Order("created_at DESC")

	err = query.Offset(req.Pagination.Offset).Limit(req.Pagination.Limit).Find(&products).Error
	if err != nil {
		return
	}

	paging = *req.Pagination

	return
}

func (_i *productsRepository) FindOne(id uint) (product *entity.Products, err error) {
	product = &entity.Products{}
	err = _i.DB.DB.Where("id = ? AND is_active = ?", id, true).First(product).Error
	return
}

func (_i *productsRepository) Create(product *entity.Products) (productReturn *entity.Products, err error) {
	if err = _i.DB.DB.Create(product).Error; err != nil {
		return
	}
	productReturn = product
	return
}

func (_i *productsRepository) Update(id uint, product *entity.Products) (err error) {
	err = _i.DB.DB.Model(&entity.Products{}).Where("id = ?", id).Updates(product).Error
	return
}

func (_i *productsRepository) Delete(id uint) (err error) {
	err = _i.DB.DB.Model(&entity.Products{}).Where("id = ?", id).Update("is_active", false).Error
	return
}

func (_i *productsRepository) FindByThumbnailPath(thumbnailPath string) (product *entity.Products, err error) {
	product = &entity.Products{}
	err = _i.DB.DB.Where("thumbnail_path LIKE ? AND is_active = ?", "%"+thumbnailPath, true).First(product).Error
	return
}

