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

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

// AddCareRecord 添加养护记录：完成当前任务 + 生成下一期任务 + 更新统计
func (l *AddCareRecordLogic) AddCareRecord(in *plant.AddCareRecordReq) (*plant.CommonResp, error) {
	txErr := l.svcCtx.DB.Transaction(func(tx *gorm.DB) error {
		// 1. 查找计划信息（获取 period 和图标用于生成下一任务）
		var plan plantModel.CarePlan
		if err := tx.Where("id = ?", in.PlanId).First(&plan).Error; err != nil {
			return err
		}

		// 2. 保存养护记录
		record := plantModel.CareRecord{
			UserID:  in.UserId,
			PlantID: in.PlantId,
			PlanID:  in.PlanId,
			Name:    plan.Name,
			Icon:    plan.Icon,
			Remark:  in.Note,
		}
		if err := tx.Create(&record).Error; err != nil {
			return err
		}

		// 3. 把该计划当前最旧的 pending 任务标记为已完成
		tx.Model(&plantModel.CareTask{}).
			Where("plan_id = ? AND status = 1", in.PlanId).
			Order("due_date asc").
			Limit(1).
			Update("status", 2)

		// 4. 生成下一期任务（以今天为基准，+period 天）
		nextDue := time.Now().Truncate(24*time.Hour).AddDate(0, 0, plan.Period)
		nextTask := plantModel.CareTask{
			UserID:       in.UserId,
			PlantID:      in.PlantId,
			PlanID:       in.PlanId,
			Name:         plan.Name,
			Icon:         plan.Icon,
			TargetAction: plan.TargetAction,
			DueDate:      nextDue,
			Status:       1,
		}
		if err := tx.Create(&nextTask).Error; err != nil {
			return err
		}

		// 5. 更新用户 care_count 统计
		actionMap := map[string]string{
			"water":     "water_count",
			"fertilize": "fertilize_count",
			"repot":     "repot_count",
			"prune":     "prune_count",
			"photo":     "photo_count",
		}
		colName := "care_count"
		if col, ok := actionMap[plan.TargetAction]; ok {
			colName = col
		}
		tx.Model(&plantModel.UserProfile{}).
			Where("user_id = ?", in.UserId).
			Updates(map[string]interface{}{
				"care_count": gorm.Expr("care_count + 1"),
				colName:      gorm.Expr(colName + " + 1"),
			})

		return nil
	})
	if txErr != nil {
		return nil, txErr
	}
	return &plant.CommonResp{Code: 0, Msg: "ok"}, nil
}
