package repository

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

	"github.com/rs/zerolog"
)

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

type PromotionsRepository interface {
	GetAll(req request.PromotionsQueryRequest) (promotions []*entity.Promotions, paging paginator.Pagination, err error)
	FindOne(id uint) (promotion *entity.Promotions, err error)
	Create(promotion *entity.Promotions) (promotionReturn *entity.Promotions, err error)
	Update(id uint, promotion *entity.Promotions) (err error)
	Delete(id uint) (err error)
	FindByThumbnailPath(thumbnailPath string) (promotion *entity.Promotions, err error)
}

func NewPromotionsRepository(db *database.Database, log zerolog.Logger) PromotionsRepository {
	return &promotionsRepository{
		DB:  db,
		Log: log,
	}
}

func (_i *promotionsRepository) GetAll(req request.PromotionsQueryRequest) (promotions []*entity.Promotions, paging paginator.Pagination, err error) {
	var count int64

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

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

	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(&promotions).Error
	if err != nil {
		return
	}

	paging = *req.Pagination

	return
}

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

func (_i *promotionsRepository) Create(promotion *entity.Promotions) (promotionReturn *entity.Promotions, err error) {
	if err = _i.DB.DB.Create(promotion).Error; err != nil {
		return
	}
	promotionReturn = promotion
	return
}

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

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

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

