package postgres

import (
	"context"
	"time"

	"gorm.io/gorm"
	"gorm.io/gorm/clause"

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

// CardDailyUsageStore 卡日流量记录存储
// 同时供落盘任务和查询层使用
type CardDailyUsageStore struct {
	db *gorm.DB
}

func NewCardDailyUsageStore(db *gorm.DB) *CardDailyUsageStore {
	return &CardDailyUsageStore{db: db}
}

// Upsert 覆盖写入日流量记录（幂等安全）
// ON CONFLICT (iot_card_id, date) DO UPDATE SET usage_mb = EXCLUDED.usage_mb
func (s *CardDailyUsageStore) Upsert(ctx context.Context, record *model.CardDailyUsage) error {
	return s.db.WithContext(ctx).
		Clauses(clause.OnConflict{
			Columns:   []clause.Column{{Name: "iot_card_id"}, {Name: "date"}},
			DoUpdates: clause.AssignmentColumns([]string{"usage_mb", "updated_at"}),
		}).
		Create(record).Error
}

// UpsertBatch 批量覆盖写入日流量记录
func (s *CardDailyUsageStore) UpsertBatch(ctx context.Context, records []*model.CardDailyUsage) error {
	if len(records) == 0 {
		return nil
	}
	return s.db.WithContext(ctx).
		Clauses(clause.OnConflict{
			Columns:   []clause.Column{{Name: "iot_card_id"}, {Name: "date"}},
			DoUpdates: clause.AssignmentColumns([]string{"usage_mb", "updated_at"}),
		}).
		CreateInBatches(records, 200).Error
}

// ListByCardIDAndDateRange 查询卡在日期范围内的日流量记录
func (s *CardDailyUsageStore) ListByCardIDAndDateRange(ctx context.Context, cardID uint, startDate, endDate time.Time) ([]*model.CardDailyUsage, error) {
	var records []*model.CardDailyUsage
	if err := s.db.WithContext(ctx).
		Where("iot_card_id = ? AND date >= ? AND date <= ?", cardID, startDate, endDate).
		Order("date ASC").
		Find(&records).Error; err != nil {
		return nil, err
	}
	return records, nil
}
