package postgres

import (
	"context"
	"time"

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

type ShopSeriesAllocationConfigStore struct {
	db *gorm.DB
}

func NewShopSeriesAllocationConfigStore(db *gorm.DB) *ShopSeriesAllocationConfigStore {
	return &ShopSeriesAllocationConfigStore{db: db}
}

func (s *ShopSeriesAllocationConfigStore) Create(ctx context.Context, config *model.ShopSeriesAllocationConfig) error {
	return s.db.WithContext(ctx).Create(config).Error
}

func (s *ShopSeriesAllocationConfigStore) GetEffective(ctx context.Context, allocationID uint, at time.Time) (*model.ShopSeriesAllocationConfig, error) {
	var config model.ShopSeriesAllocationConfig
	err := s.db.WithContext(ctx).
		Where("allocation_id = ?", allocationID).
		Where("effective_from <= ?", at).
		Where("effective_to IS NULL OR effective_to > ?", at).
		First(&config).Error
	if err != nil {
		return nil, err
	}
	return &config, nil
}

func (s *ShopSeriesAllocationConfigStore) GetLatestVersion(ctx context.Context, allocationID uint) (*model.ShopSeriesAllocationConfig, error) {
	var config model.ShopSeriesAllocationConfig
	err := s.db.WithContext(ctx).
		Where("allocation_id = ?", allocationID).
		Order("version DESC").
		First(&config).Error
	if err != nil {
		return nil, err
	}
	return &config, nil
}

func (s *ShopSeriesAllocationConfigStore) InvalidateCurrent(ctx context.Context, allocationID uint, effectiveTo time.Time) error {
	return s.db.WithContext(ctx).
		Model(&model.ShopSeriesAllocationConfig{}).
		Where("allocation_id = ? AND effective_to IS NULL", allocationID).
		Update("effective_to", effectiveTo).Error
}

func (s *ShopSeriesAllocationConfigStore) List(ctx context.Context, allocationID uint) ([]*model.ShopSeriesAllocationConfig, error) {
	var configs []*model.ShopSeriesAllocationConfig
	err := s.db.WithContext(ctx).
		Where("allocation_id = ?", allocationID).
		Order("version DESC").
		Find(&configs).Error
	if err != nil {
		return nil, err
	}
	return configs, nil
}
