package postgres

import (
	"context"

	"github.com/break/junhong_cmp_fiber/internal/model"
	"github.com/break/junhong_cmp_fiber/internal/store"
	"github.com/break/junhong_cmp_fiber/pkg/constants"
	"github.com/redis/go-redis/v9"
	"gorm.io/gorm"
)

type CommissionWithdrawalSettingStore struct {
	db    *gorm.DB
	redis *redis.Client
}

func NewCommissionWithdrawalSettingStore(db *gorm.DB, redis *redis.Client) *CommissionWithdrawalSettingStore {
	return &CommissionWithdrawalSettingStore{
		db:    db,
		redis: redis,
	}
}

func (s *CommissionWithdrawalSettingStore) Create(ctx context.Context, setting *model.CommissionWithdrawalSetting) error {
	return s.db.WithContext(ctx).Create(setting).Error
}

func (s *CommissionWithdrawalSettingStore) CreateWithTx(ctx context.Context, tx *gorm.DB, setting *model.CommissionWithdrawalSetting) error {
	return tx.WithContext(ctx).Create(setting).Error
}

func (s *CommissionWithdrawalSettingStore) GetByID(ctx context.Context, id uint) (*model.CommissionWithdrawalSetting, error) {
	var setting model.CommissionWithdrawalSetting
	if err := s.db.WithContext(ctx).First(&setting, id).Error; err != nil {
		return nil, err
	}
	return &setting, nil
}

func (s *CommissionWithdrawalSettingStore) GetCurrent(ctx context.Context) (*model.CommissionWithdrawalSetting, error) {
	var setting model.CommissionWithdrawalSetting
	if err := s.db.WithContext(ctx).Where("is_active = ?", true).First(&setting).Error; err != nil {
		return nil, err
	}
	return &setting, nil
}

func (s *CommissionWithdrawalSettingStore) List(ctx context.Context, opts *store.QueryOptions) ([]*model.CommissionWithdrawalSetting, int64, error) {
	var settings []*model.CommissionWithdrawalSetting
	var total int64

	query := s.db.WithContext(ctx).Model(&model.CommissionWithdrawalSetting{})

	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	if opts == nil {
		opts = &store.QueryOptions{
			Page:     1,
			PageSize: constants.DefaultPageSize,
		}
	}
	offset := (opts.Page - 1) * opts.PageSize
	query = query.Offset(offset).Limit(opts.PageSize).Order("created_at DESC")

	if err := query.Find(&settings).Error; err != nil {
		return nil, 0, err
	}

	return settings, total, nil
}

func (s *CommissionWithdrawalSettingStore) DeactivateCurrentWithTx(ctx context.Context, tx *gorm.DB) error {
	return tx.WithContext(ctx).Model(&model.CommissionWithdrawalSetting{}).
		Where("is_active = ?", true).
		Update("is_active", false).Error
}
