package postgres

import (
	"context"

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

type ShopPackageAllocationPriceHistoryStore struct {
	db *gorm.DB
}

func NewShopPackageAllocationPriceHistoryStore(db *gorm.DB) *ShopPackageAllocationPriceHistoryStore {
	return &ShopPackageAllocationPriceHistoryStore{db: db}
}

func (s *ShopPackageAllocationPriceHistoryStore) Create(ctx context.Context, history *model.ShopPackageAllocationPriceHistory) error {
	return s.db.WithContext(ctx).Create(history).Error
}

func (s *ShopPackageAllocationPriceHistoryStore) BatchCreate(ctx context.Context, histories []*model.ShopPackageAllocationPriceHistory) error {
	return s.db.WithContext(ctx).CreateInBatches(histories, 500).Error
}

func (s *ShopPackageAllocationPriceHistoryStore) List(ctx context.Context, opts *store.QueryOptions, filters map[string]interface{}) ([]*model.ShopPackageAllocationPriceHistory, int64, error) {
	var histories []*model.ShopPackageAllocationPriceHistory
	var total int64

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

	if allocationID, ok := filters["allocation_id"].(uint); ok && allocationID > 0 {
		query = query.Where("allocation_id = ?", allocationID)
	}

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

	if opts == nil {
		opts = store.DefaultQueryOptions()
	}
	offset := (opts.Page - 1) * opts.PageSize
	query = query.Offset(offset).Limit(opts.PageSize)

	if opts.OrderBy != "" {
		query = query.Order(opts.OrderBy)
	} else {
		query = query.Order("effective_from DESC")
	}

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

	return histories, total, nil
}

func (s *ShopPackageAllocationPriceHistoryStore) ListByAllocation(ctx context.Context, allocationID uint) ([]*model.ShopPackageAllocationPriceHistory, error) {
	var histories []*model.ShopPackageAllocationPriceHistory
	err := s.db.WithContext(ctx).
		Where("allocation_id = ?", allocationID).
		Order("effective_from DESC").
		Find(&histories).Error
	if err != nil {
		return nil, err
	}
	return histories, nil
}
