package postgres

import (
	"context"
	"time"

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

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

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

// CreateOrUpdate 创建或更新日记录（使用 UPSERT）
// 如果同一套餐同一天已有记录，则更新；否则创建新记录
func (s *PackageUsageDailyRecordStore) CreateOrUpdate(ctx context.Context, record *model.PackageUsageDailyRecord) error {
	return s.db.WithContext(ctx).Clauses(clause.OnConflict{
		Columns: []clause.Column{
			{Name: "package_usage_id"},
			{Name: "date"},
		},
		DoUpdates: clause.AssignmentColumns([]string{
			"daily_usage_mb",
			"cumulative_usage_mb",
			"updated_at",
		}),
	}).Create(record).Error
}

// GetByDateRange 按日期范围查询日记录
// startDate 和 endDate 都是可选的，如果为 nil 则不限制
func (s *PackageUsageDailyRecordStore) GetByDateRange(ctx context.Context, packageUsageID uint, startDate, endDate *time.Time) ([]*model.PackageUsageDailyRecord, error) {
	var records []*model.PackageUsageDailyRecord
	query := s.db.WithContext(ctx).
		Where("package_usage_id = ?", packageUsageID).
		Order("date ASC")

	if startDate != nil {
		query = query.Where("date >= ?", *startDate)
	}
	if endDate != nil {
		query = query.Where("date <= ?", *endDate)
	}

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

// GetByDate 查询指定日期的日记录
func (s *PackageUsageDailyRecordStore) GetByDate(ctx context.Context, packageUsageID uint, date time.Time) (*model.PackageUsageDailyRecord, error) {
	var record model.PackageUsageDailyRecord
	if err := s.db.WithContext(ctx).
		Where("package_usage_id = ? AND date = ?", packageUsageID, date).
		First(&record).Error; err != nil {
		return nil, err
	}
	return &record, nil
}

// GetLatestRecord 获取最近的一条日记录
func (s *PackageUsageDailyRecordStore) GetLatestRecord(ctx context.Context, packageUsageID uint) (*model.PackageUsageDailyRecord, error) {
	var record model.PackageUsageDailyRecord
	if err := s.db.WithContext(ctx).
		Where("package_usage_id = ?", packageUsageID).
		Order("date DESC").
		First(&record).Error; err != nil {
		return nil, err
	}
	return &record, nil
}
