package packagepkg

import (
	"context"
	"time"

	"github.com/break/junhong_cmp_fiber/internal/model"
	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	"github.com/break/junhong_cmp_fiber/internal/store/postgres"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
	"github.com/redis/go-redis/v9"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

type DailyRecordService struct {
	db                      *gorm.DB
	redis                   *redis.Client
	packageUsageDailyRecord *postgres.PackageUsageDailyRecordStore
	logger                  *zap.Logger
}

func NewDailyRecordService(
	db *gorm.DB,
	redis *redis.Client,
	packageUsageDailyRecord *postgres.PackageUsageDailyRecordStore,
	logger *zap.Logger,
) *DailyRecordService {
	return &DailyRecordService{
		db:                      db,
		redis:                   redis,
		packageUsageDailyRecord: packageUsageDailyRecord,
		logger:                  logger,
	}
}

// GetDailyRecords 任务 13.2-13.5: 查询套餐流量详单
// 查询指定套餐使用记录的日流量明细
func (s *DailyRecordService) GetDailyRecords(ctx context.Context, packageUsageID uint, startDate, endDate string) (*dto.PackageUsageDetailResponse, error) {
	// 查询套餐使用记录
	var usage model.PackageUsage
	if err := s.db.WithContext(ctx).First(&usage, packageUsageID).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, errors.New(errors.CodeNotFound, "套餐使用记录不存在")
		}
		return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询套餐使用记录失败")
	}

	// 查询套餐信息
	var pkg model.Package
	if err := s.db.WithContext(ctx).First(&pkg, usage.PackageID).Error; err != nil {
		return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询套餐信息失败")
	}

	// 任务 13.4: 查询日记录
	var records []*model.PackageUsageDailyRecord
	query := s.db.WithContext(ctx).Where("package_usage_id = ?", packageUsageID)

	// 如果提供了日期范围，添加过滤条件
	if startDate != "" {
		start, err := time.Parse("2006-01-02", startDate)
		if err != nil {
			return nil, errors.New(errors.CodeInvalidParam, "开始日期格式错误")
		}
		query = query.Where("date >= ?", start)
	}

	if endDate != "" {
		end, err := time.Parse("2006-01-02", endDate)
		if err != nil {
			return nil, errors.New(errors.CodeInvalidParam, "结束日期格式错误")
		}
		query = query.Where("date <= ?", end)
	}

	if err := query.Order("date ASC").Find(&records).Error; err != nil {
		return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询日流量记录失败")
	}

	// 任务 13.5: 组装响应 DTO
	recordResponses := make([]dto.PackageUsageDailyRecordResponse, len(records))
	var totalUsageMB int64

	for i, record := range records {
		recordResponses[i] = dto.PackageUsageDailyRecordResponse{
			Date:              record.Date.Format("2006-01-02"),
			DailyUsageMB:      record.DailyUsageMB,
			CumulativeUsageMB: record.CumulativeUsageMB,
		}
		totalUsageMB += int64(record.DailyUsageMB)
	}

	response := &dto.PackageUsageDetailResponse{
		PackageUsageID: packageUsageID,
		PackageName:    pkg.PackageName,
		Records:        recordResponses,
		TotalUsageMB:   totalUsageMB,
	}

	return response, nil
}
