package service

import (
	"errors"
	"jaecoo-be/app/module/galleries/mapper"
	"jaecoo-be/app/module/galleries/repository"
	"jaecoo-be/app/module/galleries/request"
	"jaecoo-be/app/module/galleries/response"
	"jaecoo-be/config/config"
	"jaecoo-be/utils/paginator"

	"github.com/rs/zerolog"
)

type galleriesService struct {
	Repo repository.GalleriesRepository
	Log  zerolog.Logger
	Cfg  *config.Config
}

type GalleriesService interface {
	GetAll(req request.GalleriesQueryRequest) (galleries []*response.GalleriesResponse, paging paginator.Pagination, err error)
	GetOne(id uint) (gallery *response.GalleriesResponse, err error)
	Create(req request.GalleriesCreateRequest) (gallery *response.GalleriesResponse, err error)
	Update(id uint, req request.GalleriesUpdateRequest) (gallery *response.GalleriesResponse, err error)
	Delete(id uint) (err error)
}

func NewGalleriesService(repo repository.GalleriesRepository, log zerolog.Logger, cfg *config.Config) GalleriesService {
	return &galleriesService{
		Repo: repo,
		Log:  log,
		Cfg:  cfg,
	}
}

func (_i *galleriesService) GetAll(req request.GalleriesQueryRequest) (galleries []*response.GalleriesResponse, paging paginator.Pagination, err error) {
	galleriesEntity, paging, err := _i.Repo.GetAll(req)
	if err != nil {
		return
	}

	host := _i.Cfg.App.Domain

	for _, gallery := range galleriesEntity {
		galleries = append(galleries, mapper.GalleriesResponseMapper(gallery, host))
	}

	return
}

func (_i *galleriesService) GetOne(id uint) (gallery *response.GalleriesResponse, err error) {
	galleryEntity, err := _i.Repo.FindOne(id)
	if err != nil {
		return
	}

	if galleryEntity == nil {
		err = errors.New("gallery not found")
		return
	}

	host := _i.Cfg.App.Domain

	gallery = mapper.GalleriesResponseMapper(galleryEntity, host)
	return
}

func (_i *galleriesService) Create(req request.GalleriesCreateRequest) (gallery *response.GalleriesResponse, err error) {
	galleryEntity := req.ToEntity()
	isActive := true
	galleryEntity.IsActive = &isActive

	galleryEntity, err = _i.Repo.Create(galleryEntity)
	if err != nil {
		return
	}

	host := _i.Cfg.App.Domain

	gallery = mapper.GalleriesResponseMapper(galleryEntity, host)
	return
}

func (_i *galleriesService) Update(id uint, req request.GalleriesUpdateRequest) (gallery *response.GalleriesResponse, err error) {
	galleryEntity := req.ToEntity()

	err = _i.Repo.Update(id, galleryEntity)
	if err != nil {
		return
	}

	galleryEntity, err = _i.Repo.FindOne(id)
	if err != nil {
		return
	}

	host := _i.Cfg.App.Domain

	gallery = mapper.GalleriesResponseMapper(galleryEntity, host)
	return
}

func (_i *galleriesService) Delete(id uint) (err error) {
	err = _i.Repo.Delete(id)
	return
}
