package application

import (
	"errors"

	"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"
	coreTypes "git.apinb.com/bsm-sdk/core/types"
	"git.apinb.com/bsm-sdk/core/utils"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func Create(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, err)
		return
	}

	// 判断应用是否已经存在（包括软删除的记录）
	db := models.DBService.Model(&models.MgtApplication{})
	if err = db.Where("title = ? or workspace = ?", request.Title, request.Workspace).First(&data).Error; err != nil {
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			infra.Response.Error(c, errcode.ErrDB)
			return
		}
		// 未找到记录（包括软删除的），检查是否有软删除的记录
		var deletedData models.MgtApplication
		// 检查 workspace 是否被软删除（workspace 有唯一索引）
		if request.Workspace != "" {
			if err = models.DBService.Unscoped().Where("workspace = ?", request.Workspace).First(&deletedData).Error; err == nil {
				// 存在软删除的记录，先物理删除它，以便可以重新创建
				if err = models.DBService.Unscoped().Delete(&deletedData).Error; err != nil {
					infra.Response.Error(c, errcode.ErrDB)
					return
				}
				printer.Info("已物理删除软删除的应用记录: ID=%d, workspace=%s", deletedData.ID, deletedData.Workspace)
			}
		}
		// 检查 title 是否被软删除（如果 title 和 workspace 不同）
		if request.Title != "" && request.Title != request.Workspace {
			if err = models.DBService.Unscoped().Where("title = ?", request.Title).First(&deletedData).Error; err == nil {
				// 存在软删除的记录，先物理删除它
				if err = models.DBService.Unscoped().Delete(&deletedData).Error; err != nil {
					infra.Response.Error(c, errcode.ErrDB)
					return
				}
				printer.Info("已物理删除软删除的应用记录: ID=%d, title=%s", deletedData.ID, deletedData.Title)
			}
		}
	} else {
		// 找到未删除的记录，说明应用已存在
		printer.Info("应用已存在: title=%s, workspace=%s", request.Title, request.Workspace)
		infra.Response.Error(c, errcode.ErrAlreadyExists)
		return
	}

	// 新增应用
	var dataModel = models.MgtApplication{
		Std_IICUDS:  coreTypes.Std_IICUDS{Identity: utils.UUID(), Status: 1},
		Title:       request.Title,
		Workspace:   request.Workspace,
		Description: request.Description,
	}
	if err = models.DBService.Model(&models.MgtApplication{}).Create(&dataModel).Error; err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

	printer.Info("应用创建成功: ID=%d, workspace=%s", dataModel.ID, dataModel.Workspace)
	infra.Response.Success(c, types.IdResp{Id: dataModel.ID, Identity: dataModel.Identity})
}
