package sop_stage

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"wechat-api/ent/sopstage"
	"wechat-api/internal/utils/dberrorhandler"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"

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

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

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

func (l *MoveSopStageLogic) MoveSopStage(req *types.SopStageMoveReq) (resp *types.BaseMsgResp, err error) {
	// 获取待移动阶段顺序
	data, err := l.svcCtx.DB.SopStage.Get(l.ctx, *req.Id)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}
	taskId := data.TaskID
	currentIndexSort := data.IndexSort
	targetIndexSort := currentIndexSort + *req.Offset

	// 开始一个新的事务
	tx, err := l.svcCtx.DB.Tx(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	// 确保在函数返回时回滚事务，除非提交事务成功
	defer func() {
		if err != nil {
			if rbErr := tx.Rollback(); rbErr != nil {
				l.Logger.Errorf("tx rollback error: %v", rbErr)
			}
		} else {
			if commitErr := tx.Commit(); commitErr != nil {
				err = commitErr
			}
		}
	}()

	// 更改目标阶段顺序
	affected, err := tx.SopStage.Update().
		Where(
			sopstage.TaskID(taskId),
			sopstage.IndexSort(targetIndexSort),
		).
		SetNotNilIndexSort(&currentIndexSort).
		Save(l.ctx)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	if affected == 0 {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	// 更改待移动阶段顺序
	err = tx.SopStage.UpdateOneID(*req.Id).
		SetNotNilIndexSort(&targetIndexSort).
		Exec(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	return &types.BaseMsgResp{Msg: errormsg.UpdateSuccess}, nil
}
