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 GetTodayTaskListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func (l *GetTodayTaskListLogic) GetTodayTaskList(in *plant.GetProfileReq) (*plant.CareTaskListResp, error) {
	now := time.Now()
	todayStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
	todayEnd := todayStart.Add(24 * time.Hour)

	var tasks []plantModel.CareTask
	if err := l.svcCtx.DB.Where(
		"user_id = ? AND ((status = 1 AND due_date < ?) OR (status = 2 AND completed_at >= ? AND completed_at < ?))",
		in.UserId, todayEnd, todayStart, todayEnd,
	).Order("due_date asc").Find(&tasks).Error; err != nil {
		return nil, err
	}
	list := make([]*plant.CareTaskInfo, 0, len(tasks))
	for _, t := range tasks {
		list = append(list, &plant.CareTaskInfo{
			Id: t.ID, PlantId: t.PlantID, PlanId: t.PlanID,
			Name: t.Name, Icon: t.Icon, TargetAction: t.TargetAction,
			DueDate: t.DueDate.Format("2006-01-02"), Status: int32(t.Status),
		})
	}
	return &plant.CareTaskListResp{List: list, Total: int64(len(list))}, nil
}
