package service

import (
	"context"
	"opencatd-open/internal/dao"
	dto "opencatd-open/internal/dto/team"
	"opencatd-open/internal/model"
	"opencatd-open/pkg/config"
	"time"

	"gorm.io/gorm"
)

var _ UsageService = (*usageService)(nil)

type UsageService interface {
	ListByUserID(ctx context.Context, userID int64, limit, offset int) ([]*model.Usage, error)
	ListByCapability(ctx context.Context, capability string, limit, offset int) ([]*model.Usage, error)
	ListByDateRange(ctx context.Context, start, end time.Time, filters map[string]interface{}) ([]*dto.UsageInfo, error)

	Delete(ctx context.Context, id int64) error
}

type usageService struct {
	ctx context.Context
	cfg *config.Config
	db  *gorm.DB

	usageDAO      dao.UsageRepository
	dailyUsageDAO dao.DailyUsageRepository
}

func NewUsageService(ctx context.Context, cfg *config.Config, db *gorm.DB, usageRepo dao.UsageRepository, dailyUsageRepo dao.DailyUsageRepository) UsageService {
	srv := &usageService{
		ctx: ctx,
		cfg: cfg,
		db:  db,

		usageDAO:      usageRepo,
		dailyUsageDAO: dailyUsageRepo,
	}

	// 启动异步处理goroutine

	return srv
}

func (s *usageService) ListByUserID(ctx context.Context, userID int64, limit int, offset int) ([]*model.Usage, error) {
	return s.usageDAO.ListByUserID(ctx, userID, limit, offset)
}

func (s *usageService) ListByCapability(ctx context.Context, capability string, limit, offset int) ([]*model.Usage, error) {
	return s.usageDAO.ListByCapability(ctx, capability, limit, offset)
}

func (s *usageService) ListByDateRange(ctx context.Context, start, end time.Time, filters map[string]interface{}) ([]*dto.UsageInfo, error) {
	return s.dailyUsageDAO.StatUserUsages(ctx, start, end, filters)
}

func (s *usageService) Delete(ctx context.Context, id int64) error {
	return s.usageDAO.Delete(ctx, id)
}
