package application

import (
	"errors"

	"bsm/full/module/base/mgt/internal/impl"
	"bsm/full/module/base/mgt/internal/libs"
	"bsm/full/module/base/mgt/internal/models"
	"bsm/full/module/base/mgt/internal/types"

	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/infra"
	"git.apinb.com/bsm-sdk/core/printer"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func Midify(c *gin.Context) {
	var (
		request = types.ApplicationRequest{}
		data    = models.MgtApplication{}
	)

	// 解析JSON请求
	err := c.ShouldBindJSON(&request)
	if err != nil {
		infra.Response.Error(c, errcode.ErrJsonUnmarshal)
		return
	}

	// 参数验证
	if err := libs.ValidateStruct(&request); err != nil {
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}

	if request.ID == 0 {
		printer.Error("更新应用参数异常: ID不能为空")
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}

	// 检查workspace是否已被其他应用使用
	if request.Workspace != "" {
		if err := impl.DBService.Model(&models.MgtApplication{}).Where("workspace=? and id<>?", request.Workspace, request.ID).First(&data).Error; err != nil {
			if !errors.Is(err, gorm.ErrRecordNotFound) {
				infra.Response.Error(c, errcode.ErrDB)
				return
			}
		}
		if data.ID != 0 {
			printer.Info("工作空间已被使用: workspace=%s", request.Workspace)
			infra.Response.Error(c, errcode.ErrAlreadyExists)
			return
		}
	}

	var dataModel = models.MgtApplication{
		Title:       request.Title,
		Workspace:   request.Workspace,
		Description: request.Description,
	}
	if request.Status != 0 {
		dataModel.Status = request.Status
	}
	if err := impl.DBService.Model(&models.MgtApplication{}).Where("id = ?", request.ID).Updates(&dataModel).Error; err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

	printer.Info("应用更新成功: ID=%d", request.ID)
	infra.Response.Success(c, types.IdResp{Id: request.ID, Identity: dataModel.Identity})
}
