package logic

import (
	"context"
	"time"

	plantModel "sundynix-micro-go/app/plant/model"
	"sundynix-micro-go/app/plant/rpc/internal/svc"
	"sundynix-micro-go/app/plant/rpc/plant"

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

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

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

// 添加魏护计划
func (l *AddCarePlanLogic) AddCarePlan(in *plant.AddCarePlanReq) (*plant.CommonResp, error) {
	txErr := l.svcCtx.DB.Transaction(func(tx *gorm.DB) error {
		// 1. 创建计划
		carePlan := plantModel.CarePlan{
			UserID:       in.UserId,
			PlantID:      in.PlantId,
			Name:         in.Name,
			Icon:         in.Icon,
			Period:       int(in.Period),
			TargetAction: in.TargetAction,
		}
		if err := tx.Create(&carePlan).Error; err != nil {
			return err
		}
		// 2. 创建第一个魏护任务
		today := time.Now().Truncate(24 * time.Hour)
		dueDate := today.AddDate(0, 0, int(in.Period))
		task := plantModel.CareTask{
			UserID:       in.UserId,
			PlantID:      in.PlantId,
			PlanID:       carePlan.ID,
			Name:         in.Name,
			Icon:         in.Icon,
			TargetAction: in.TargetAction,
			DueDate:      dueDate,
			Status:       1,
		}
		return tx.Create(&task).Error
	})
	if txErr != nil {
		return nil, txErr
	}
	return &plant.CommonResp{Code: 0, Msg: "ok"}, nil
}
