package logic

import (
	"context"

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

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

// 删除植物 (级联删除魏护计划/任务/记录/图片)
func (l *DeletePlantLogic) DeletePlant(in *plant.IdsReq) (*plant.CommonResp, error) {
	txErr := l.svcCtx.DB.Transaction(func(tx *gorm.DB) error {
		// 1. 清理图片中间表
		tx.Exec("DELETE FROM sundynix_my_plant_oss WHERE sundynix_my_plant_id IN ?", in.Ids)
		// 2. 删除魏护计划
		if err := tx.Unscoped().Where("plant_id IN ?", in.Ids).Delete(&plantModel.CarePlan{}).Error; err != nil {
			return err
		}
		// 3. 删除魏护任务
		if err := tx.Unscoped().Where("plant_id IN ?", in.Ids).Delete(&plantModel.CareTask{}).Error; err != nil {
			return err
		}
		// 4. 删除魏护记录
		if err := tx.Unscoped().Where("plant_id IN ?", in.Ids).Delete(&plantModel.CareRecord{}).Error; err != nil {
			return err
		}
		// 5. 删除成长记录
		if err := tx.Unscoped().Where("plant_id IN ?", in.Ids).Delete(&plantModel.GrowthRecord{}).Error; err != nil {
			return err
		}
		// 6. 删除植物本身
		return tx.Unscoped().Where("id IN ?", in.Ids).Delete(&plantModel.MyPlant{}).Error
	})
	if txErr != nil {
		return nil, txErr
	}
	return &plant.CommonResp{Code: 0, Msg: "ok"}, nil
}
