package repository

import (
	"campaign-pool-be/app/database"
	"campaign-pool-be/app/database/entity"
	"campaign-pool-be/app/module/campaign_types/request"
	"campaign-pool-be/utils/paginator"
	utilSvc "campaign-pool-be/utils/service"
	"fmt"
	"strings"

	"github.com/rs/zerolog"
)

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

// CampaignTypesRepository define interface of ICampaignTypesRepository
type CampaignTypesRepository interface {
	GetAll(req request.CampaignTypesQueryRequest) (campaignTypess []*entity.CampaignTypes, paging paginator.Pagination, err error)
	FindOne(id uint) (campaignTypes *entity.CampaignTypes, err error)
	Create(campaignTypes *entity.CampaignTypes) (campaignTypesReturn *entity.CampaignTypes, err error)
	Update(id uint, campaignTypes *entity.CampaignTypes) (err error)
	Delete(id uint) (err error)
}

func NewCampaignTypesRepository(db *database.Database, log zerolog.Logger) CampaignTypesRepository {
	return &campaignTypesRepository{
		DB:  db,
		Log: log,
	}
}

// implement interface of ICampaignTypesRepository
func (_i *campaignTypesRepository) GetAll(req request.CampaignTypesQueryRequest) (campaignTypess []*entity.CampaignTypes, paging paginator.Pagination, err error) {
	var count int64

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

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

	if req.Pagination.SortBy != "" {
		direction := "ASC"
		if req.Pagination.Sort == "desc" {
			direction = "DESC"
		}
		query.Order(fmt.Sprintf("%s %s", req.Pagination.SortBy, direction))
	} else {
		direction := "DESC"
		sortBy := "created_at"
		query.Order(fmt.Sprintf("%s %s", sortBy, direction))
	}

	req.Pagination.Count = count
	req.Pagination = paginator.Paging(req.Pagination)

	err = query.Offset(req.Pagination.Offset).Limit(req.Pagination.Limit).Find(&campaignTypess).Error
	if err != nil {
		return
	}

	paging = *req.Pagination

	return
}

func (_i *campaignTypesRepository) FindOne(id uint) (campaignTypes *entity.CampaignTypes, err error) {
	query := _i.DB.DB.Where("id = ?", id)

	if err := query.First(&campaignTypes).Error; err != nil {
		return nil, err
	}

	return campaignTypes, nil
}

func (_i *campaignTypesRepository) Create(campaignTypes *entity.CampaignTypes) (campaignTypesReturn *entity.CampaignTypes, err error) {
	result := _i.DB.DB.Create(campaignTypes)
	return campaignTypes, result.Error
}

func (_i *campaignTypesRepository) Update(id uint, campaignTypes *entity.CampaignTypes) (err error) {
	campaignTypesMap, err := utilSvc.StructToMap(campaignTypes)
	if err != nil {
		return err
	}
	query := _i.DB.DB.Model(&entity.CampaignTypes{}).Where(&entity.CampaignTypes{ID: id})
	return query.Updates(campaignTypesMap).Error
}

func (_i *campaignTypesRepository) Delete(id uint) error {
	return _i.DB.DB.Delete(&entity.CampaignTypes{}, id).Error
}

