package repository

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

	"github.com/rs/zerolog"
)

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

// SubscriptionRepository define interface of ISubscriptionRepository
type SubscriptionRepository interface {
	GetAll(req request.SubscriptionQueryRequest) (subscriptions []*entity.Subscription, paging paginator.Pagination, err error)
	FindOne(id uint) (subscription *entity.Subscription, err error)
	Create(subscription *entity.Subscription) (subscriptionReturn *entity.Subscription, err error)
	Update(id uint, subscription *entity.Subscription) (err error)
	Delete(id uint) (err error)
}

func NewSubscriptionRepository(db *database.Database, logger zerolog.Logger) SubscriptionRepository {
	return &subscriptionRepository{
		DB:  db,
		Log: logger,
	}
}

// implement interface of ISubscriptionRepository
func (_i *subscriptionRepository) GetAll(req request.SubscriptionQueryRequest) (subscriptions []*entity.Subscription, paging paginator.Pagination, err error) {
	var count int64

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

	query = query.Where("is_active = ?", true)

	if req.Email != nil && *req.Email != "" {
		email := strings.ToLower(*req.Email)
		query = query.Where("LOWER(email) LIKE ?", "%"+strings.ToLower(email)+"%")
	}
	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))
	}

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

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

	paging = *req.Pagination

	return
}

func (_i *subscriptionRepository) FindOne(id uint) (subscription *entity.Subscription, err error) {
	query := _i.DB.DB.Where("id = ?", id)

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

	return subscription, nil
}

func (_i *subscriptionRepository) Create(subscription *entity.Subscription) (subscriptionReturn *entity.Subscription, err error) {
	result := _i.DB.DB.Create(subscription)
	return subscription, result.Error
}

func (_i *subscriptionRepository) Update(id uint, subscription *entity.Subscription) (err error) {
	query := _i.DB.DB.Model(&entity.Subscription{}).Where(&entity.Subscription{ID: id})
	return query.Updates(subscription).Error
}

func (_i *subscriptionRepository) Delete(id uint) error {
	query := _i.DB.DB.Model(&entity.Subscription{}).Where("id = ?", id)
	return query.Delete(&entity.Subscription{}).Error
}
