package repository

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

	"github.com/rs/zerolog"
)

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

type BannersRepository interface {
	GetAll(req request.BannersQueryRequest) (banners []*entity.Banners, paging paginator.Pagination, err error)
	FindOne(id uint) (banner *entity.Banners, err error)
	Create(banner *entity.Banners) (bannerReturn *entity.Banners, err error)
	Update(id uint, banner *entity.Banners) (err error)
	Delete(id uint) (err error)
	FindByThumbnailPath(thumbnailPath string) (banner *entity.Banners, err error)
}

func NewBannersRepository(db *database.Database, log zerolog.Logger) BannersRepository {
	return &bannersRepository{
		DB:  db,
		Log: log,
	}
}

func (_i *bannersRepository) GetAll(req request.BannersQueryRequest) (banners []*entity.Banners, paging paginator.Pagination, err error) {
	var count int64

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

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

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

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

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

	paging = *req.Pagination

	return
}

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

func (_i *bannersRepository) Create(banner *entity.Banners) (bannerReturn *entity.Banners, err error) {
	if err = _i.DB.DB.Create(banner).Error; err != nil {
		return
	}
	bannerReturn = banner
	return
}

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

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

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