package repository

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

	"github.com/rs/zerolog"
)

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

type GalleryFilesRepository interface {
	GetAll(req request.GalleryFilesQueryRequest) (files []*entity.GalleryFiles, paging paginator.Pagination, err error)
	FindOne(id uint) (file *entity.GalleryFiles, err error)
	Create(file *entity.GalleryFiles) (fileReturn *entity.GalleryFiles, err error)
	Update(id uint, file *entity.GalleryFiles) (err error)
	Delete(id uint) (err error)
	FindByImagePath(imagePath string) (file *entity.GalleryFiles, err error)
}

func NewGalleryFilesRepository(db *database.Database, log zerolog.Logger) GalleryFilesRepository {
	return &galleryFilesRepository{
		DB:  db,
		Log: log,
	}
}

func (_i *galleryFilesRepository) GetAll(req request.GalleryFilesQueryRequest) (files []*entity.GalleryFiles, paging paginator.Pagination, err error) {
	var count int64

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

	if req.GalleryID != nil {
		query = query.Where("gallery_id = ?", *req.GalleryID)
	}

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

	paging = *req.Pagination

	return
}

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

func (_i *galleryFilesRepository) Create(file *entity.GalleryFiles) (fileReturn *entity.GalleryFiles, err error) {
	if err = _i.DB.DB.Create(file).Error; err != nil {
		return
	}
	fileReturn = file
	return
}

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

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

func (_i *galleryFilesRepository) FindByImagePath(imagePath string) (file *entity.GalleryFiles, err error) {
	file = &entity.GalleryFiles{}
	err = _i.DB.DB.Where("image_path LIKE ? AND is_active = ?", "%"+imagePath, true).First(file).Error
	return
}

