package admin_agent

import (
	"context"
	"fmt"
	"sort"
	"time"

	"sim-server/app/main/api/internal/svc"
	"sim-server/app/main/api/internal/types"
	"sim-server/common/globalkey"

	"github.com/zeromicro/go-zero/core/logx"
)

type AdminGetAgentTrendsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAdminGetAgentTrendsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetAgentTrendsLogic {
	return &AdminGetAgentTrendsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AdminGetAgentTrendsLogic) AdminGetAgentTrends(req *types.AdminGetAgentTrendsReq) (resp *types.AdminGetAgentTrendsResp, err error) {
	// 1. Parse date parameters with default to last 30 days
	var startDate, endDate time.Time

	if req.StartDate != "" {
		startDate, err = time.Parse("2006-01-02", req.StartDate)
		if err != nil {
			return nil, fmt.Errorf("invalid start_date format: %v", err)
		}
	} else {
		// Default to 30 days ago
		startDate = time.Now().AddDate(0, 0, -30)
	}

	if req.EndDate != "" {
		endDate, err = time.Parse("2006-01-02", req.EndDate)
		if err != nil {
			return nil, fmt.Errorf("invalid end_date format: %v", err)
		}
		// Set end date to end of day
		endDate = time.Date(endDate.Year(), endDate.Month(), endDate.Day(), 23, 59, 59, 0, time.Local)
	} else {
		// Default to today
		endDate = time.Now()
	}

	// Ensure start date is before end date
	if startDate.After(endDate) {
		return nil, fmt.Errorf("start_date must be before end_date")
	}

	// 2. Query all agents in date range
	builder := l.svcCtx.AgentModel.SelectBuilder()
	builder = builder.Where("del_state = ?", globalkey.DelStateNo)
	builder = builder.Where("create_time >= ?", startDate)
	builder = builder.Where("create_time <= ?", endDate)

	agents, err := l.svcCtx.AgentModel.FindAll(l.ctx, builder, "")
	if err != nil {
		return nil, fmt.Errorf("failed to query agents: %v", err)
	}

	// 3. Group by date in Go
	dateMap := make(map[string]int64)

	for _, agent := range agents {
		date := agent.CreateTime.Format("2006-01-02")
		dateMap[date]++
	}

	// 4. Build sorted response
	dates := make([]string, 0, len(dateMap))
	counts := make([]int64, 0, len(dateMap))

	for date := range dateMap {
		dates = append(dates, date)
	}

	// Sort dates
	sort.Strings(dates)

	for _, date := range dates {
		counts = append(counts, dateMap[date])
	}

	return &types.AdminGetAgentTrendsResp{
		Dates:  dates,
		Counts: counts,
	}, nil
}
