package core

import (
	"context"
	"github.com/pkg/errors"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/models"
	"gorm.io/gorm"
	"time"

	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/svc"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/types"

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

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

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

func (l *DeleteResourceSpecLogic) DeleteResourceSpec(req *types.DeletePathId) (resp *types.CommonResp, err error) {
	// 初始化事务
	tx := l.svcCtx.DbEngin.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
			panic(r)
		}
	}()

	// 1. 检查主资源规格是否存在
	var mainSpec models.TResourceSpec
	if err := tx.Where("id = ? AND deleted_at IS NULL", req.Id).
		First(&mainSpec).
		Error; err != nil {
		tx.Rollback()
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.Errorf("资源规格不存在 (ID: %s)", req.Id)
		}
		return nil, errors.Wrapf(err, "查询资源规格失败 (ID: %s)", req.Id)
	}

	// 2. 删除主资源规格（软删除）
	if err := tx.Model(&models.TResourceSpec{}).
		Where("id = ?", req.Id).
		Update("deleted_at", time.Now()).
		Error; err != nil {
		tx.Rollback()
		return nil, errors.Wrapf(err, "删除主资源规格失败 (ID: %s)", req.Id)
	}

	// 3. 删除关联的基础资源规格（软删除）
	if err := tx.Model(&models.TBaseResourceSpec{}).
		Where("resource_spec_id = ?", req.Id).
		Update("deleted_at", time.Now()).
		Error; err != nil {
		tx.Rollback()
		return nil, errors.Wrapf(err, "删除基础资源规格失败 (ID: %s)", req.Id)
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		return nil, errors.Wrap(err, "提交事务失败")
	}

	return resp, nil
}
