package logic

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	plantModel "sundynix-micro-go/app/plant/model"
	"sundynix-micro-go/app/plant/rpc/internal/svc"
	"sundynix-micro-go/app/plant/rpc/plant"
	"time"
)

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

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

func (l *GetAiChatQuotaLogic) GetAiChatQuota(in *plant.GetProfileReq) (*plant.AiQuotaResp, error) {
	now := time.Now()
	todayStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
	var used int64
	l.svcCtx.DB.Model(&plantModel.AiChatHistory{}).
		Where("user_id = ? AND created_at >= ?", in.UserId, todayStart).
		Count(&used)
	limit := l.svcCtx.Config.Ai.DailyQuota
	if limit <= 0 {
		limit = 20
	}
	remaining := limit - used
	if remaining < 0 {
		remaining = 0
	}
	return &plant.AiQuotaResp{Remaining: remaining, Total: limit, Used: used, Limit: limit}, nil
}
