package postgres

import (
	"context"

	"github.com/break/junhong_cmp_fiber/internal/model"
	"gorm.io/gorm"
)

type ShopSeriesOneTimeCommissionTierStore struct {
	db *gorm.DB
}

func NewShopSeriesOneTimeCommissionTierStore(db *gorm.DB) *ShopSeriesOneTimeCommissionTierStore {
	return &ShopSeriesOneTimeCommissionTierStore{db: db}
}

func (s *ShopSeriesOneTimeCommissionTierStore) Create(ctx context.Context, tier *model.ShopSeriesOneTimeCommissionTier) error {
	return s.db.WithContext(ctx).Create(tier).Error
}

func (s *ShopSeriesOneTimeCommissionTierStore) BatchCreate(ctx context.Context, tiers []*model.ShopSeriesOneTimeCommissionTier) error {
	if len(tiers) == 0 {
		return nil
	}
	return s.db.WithContext(ctx).Create(&tiers).Error
}

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

func (s *ShopSeriesOneTimeCommissionTierStore) Update(ctx context.Context, tier *model.ShopSeriesOneTimeCommissionTier) error {
	return s.db.WithContext(ctx).Save(tier).Error
}

func (s *ShopSeriesOneTimeCommissionTierStore) Delete(ctx context.Context, id uint) error {
	return s.db.WithContext(ctx).Delete(&model.ShopSeriesOneTimeCommissionTier{}, id).Error
}

func (s *ShopSeriesOneTimeCommissionTierStore) ListByAllocationID(ctx context.Context, allocationID uint) ([]*model.ShopSeriesOneTimeCommissionTier, error) {
	var tiers []*model.ShopSeriesOneTimeCommissionTier
	if err := s.db.WithContext(ctx).
		Where("allocation_id = ?", allocationID).
		Where("status = ?", 1).
		Order("threshold_value ASC").
		Find(&tiers).Error; err != nil {
		return nil, err
	}
	return tiers, nil
}

func (s *ShopSeriesOneTimeCommissionTierStore) DeleteByAllocationID(ctx context.Context, allocationID uint) error {
	return s.db.WithContext(ctx).
		Where("allocation_id = ?", allocationID).
		Delete(&model.ShopSeriesOneTimeCommissionTier{}).Error
}
