package department

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"
	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.DptReq{}
		data    = models.MgtDepartment{}
	)

	// 解析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.Workspace == "" {
		printer.Error("新增部门参数异常: workspace 不能为空")
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}
	if request.Name == "" {
		printer.Error("新增部门参数异常: 部门名称不能为空")
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}

	appModel := models.MgtApplication{Workspace: request.Workspace}
	appId, err := appModel.WorkspaceToId()
	if err != nil {
		printer.Error("未获取到应用: workspace=%s, err=%v", request.Workspace, err)
		infra.Response.Error(c, errcode.ErrRecordNotFound)
		return
	}

	// 同一应用下部门名称唯一
	if err = impl.DBService.Model(&models.MgtDepartment{}).
		Where("app_id = ? and name = ?", appId, request.Name).First(&data).Error; err != nil {
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			infra.Response.Error(c, errcode.ErrDB)
			return
		}
	} else {
		printer.Info("该应用下部门已存在: workspace=%s, name=%s", request.Workspace, request.Name)
		infra.Response.Error(c, errcode.ErrAlreadyExists)
		return
	}

	// 若有父部门，校验父部门属于同一应用
	if request.ParentID > 0 {
		var parent models.MgtDepartment
		if err = impl.DBService.Select("id", "app_id").Where("id = ?", request.ParentID).First(&parent).Error; err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				infra.Response.Error(c, errcode.ErrRecordNotFound)
				return
			}
			infra.Response.Error(c, errcode.ErrDB)
			return
		}
		if parent.AppID != appId {
			printer.Error("父部门不属于当前应用")
			infra.Response.Error(c, errcode.ErrInvalidArgument)
			return
		}
	}

	// 新增部门（归属当前应用）
	var dataModel = models.MgtDepartment{
		Std_IICUDS: coreTypes.Std_IICUDS{Identity: utils.ULID(), Status: 1},
		AppID:      appId,
		ParentID:   request.ParentID,
		LeaderID:   request.LeaderID,
		Name:       request.Name,
	}
	if err = impl.DBService.Create(&dataModel).Error; err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

	printer.Info("部门创建成功: ID=%d, name=%s", dataModel.ID, dataModel.Name)
	infra.Response.Success(c, types.IdResp{Id: dataModel.ID, Identity: dataModel.Identity})
}
