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"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func Modify(c *gin.Context) {
	var (
		request = types.DptReq{}
		data    = models.MgtDepartment{}
	)

	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 {
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}

	if err = impl.DBService.Select("id", "app_id", "identity").Where("id = ?", request.ID).First(&data).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			infra.Response.Error(c, errcode.ErrRecordNotFound)
			return
		}
		infra.Response.Error(c, errcode.ErrDB)
		return
	}
	appId := data.AppID

	if request.ParentID > 0 {
		if request.ParentID == request.ID {
			printer.Error("self-reference is not allowed: id=%d", request.ID)
			infra.Response.Error(c, errcode.ErrInvalidArgument)
			return
		}
		descendantIds, err := getDepartmentIdsRecursive(impl.DBService, appId, request.ID)
		if err != nil {
			infra.Response.Error(c, errcode.ErrDB)
			return
		}
		for _, id := range descendantIds {
			if id == request.ParentID {
				printer.Error("self-reference is not allowed: parent_id=%d", request.ParentID)
				infra.Response.Error(c, errcode.ErrInvalidArgument)
				return
			}
		}
	}

	if request.Name != "" {
		var exist models.MgtDepartment
		if err = impl.DBService.Model(&models.MgtDepartment{}).
			Where("app_id = ? and name = ? and id <> ?", appId, request.Name, request.ID).First(&exist).Error; err == nil {
			infra.Response.Error(c, errcode.ErrAlreadyExists)
			return
		}
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			infra.Response.Error(c, errcode.ErrDB)
			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.ErrInvalidArgument)
				return
			}
			infra.Response.Error(c, errcode.ErrDB)
			return
		}
		if parent.AppID != appId {
			printer.Error("parent department not found: parent_id=%d, app_id=%d", request.ParentID, appId)
			infra.Response.Error(c, errcode.ErrInvalidArgument)
			return
		}
	}

	var dataModel = models.MgtDepartment{
		Name:       request.Name,
		ParentID:   request.ParentID,
		LeaderID:   request.LeaderID,
		Std_IICUDS: coreTypes.Std_IICUDS{Status: request.Status},
	}
	if err := impl.DBService.Model(&models.MgtDepartment{}).Where("id = ?", request.ID).Updates(&dataModel).Error; err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

	printer.Info("department modified: id=%d", request.ID)
	infra.Response.Success(c, types.IdResp{Id: request.ID, Identity: data.Identity})
}
