package repository

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

	"github.com/rs/zerolog"
)

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

type GalleriesRepository interface {
	GetAll(req request.GalleriesQueryRequest) (galleries []*entity.Galleries, paging paginator.Pagination, err error)
	FindOne(id uint) (gallery *entity.Galleries, err error)
	Create(gallery *entity.Galleries) (galleryReturn *entity.Galleries, err error)
	Update(id uint, gallery *entity.Galleries) (err error)
	Delete(id uint) (err error)
}

func NewGalleriesRepository(db *database.Database, log zerolog.Logger) GalleriesRepository {
	return &galleriesRepository{
		DB:  db,
		Log: log,
	}
}

func (_i *galleriesRepository) GetAll(req request.GalleriesQueryRequest) (galleries []*entity.Galleries, paging paginator.Pagination, err error) {
	var count int64

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

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

	paging = *req.Pagination

	return
}

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

func (_i *galleriesRepository) Create(gallery *entity.Galleries) (galleryReturn *entity.Galleries, err error) {
	if err = _i.DB.DB.Create(gallery).Error; err != nil {
		return
	}
	galleryReturn = gallery
	return
}

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

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