package permission

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 Midify(c *gin.Context) {
	var (
		request = types.PermissionRequest{}
		data    = models.MgtPermission{}
		app     models.MgtApplication
	)

	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
	}

	if request.Workspace != "" {
		app = models.MgtApplication{Workspace: request.Workspace}
		appId, err := app.WorkspaceToId()
		if err != nil {
			printer.Error("获取appId异常: %v", err)
			infra.Response.Error(c, errcode.ErrRecordNotFound)
			return
		}

		if request.Code != "" {
			data = models.MgtPermission{}
			if err := impl.DBService.Model(&models.MgtPermission{}).Where("code = ? AND app_id = ? AND id <> ?", request.Code, appId, 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("权限code已存在: code=%s", request.Code)
				infra.Response.Error(c, errcode.ErrAlreadyExists)
				return
			}
		}

		var dataModel = models.MgtPermission{
			Std_IICUDS:  coreTypes.Std_IICUDS{Status: request.Status},
			Code:        request.Code,
			Title:       request.Title,
			Appid:       appId,
			ParentID:    request.ParentID,
			MenuPath:    request.MenuPath,
			MenuIcon:    request.MenuIcon,
			Type:        request.Type,
			Component:   request.Component,
			Description: request.Description,
			IsWebPage:   request.IsWebPage,
			IsNewTab:    request.IsNewTab,
			IsFull:      request.IsFull,
			HideMenu:    request.HideMenu,
			WebUrl:      request.WebUrl,
		}

		updateFields := []string{"status", "code", "title", "app_id", "parent_id", "menu_path", "menu_icon", "type", "component", "description", "is_web_page", "is_new_tab", "is_full", "hide_menu", "web_url"}
		if err := impl.DBService.Model(&models.MgtPermission{}).Where("id = ?", request.ID).Select(updateFields).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})
		return
	}

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

	if request.Code != "" {
		data = models.MgtPermission{}
		if err := impl.DBService.Model(&models.MgtPermission{}).
			Where("code = ? AND app_id = ? AND id <> ?", request.Code, existing.Appid, 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("权限code已存在: code=%s", request.Code)
			infra.Response.Error(c, errcode.ErrAlreadyExists)
			return
		}
	}

	var dataModel = models.MgtPermission{
		Std_IICUDS:  coreTypes.Std_IICUDS{Status: request.Status},
		Code:        request.Code,
		Title:       request.Title,
		ParentID:    request.ParentID,
		MenuPath:    request.MenuPath,
		MenuIcon:    request.MenuIcon,
		Type:        request.Type,
		Component:   request.Component,
		Description: request.Description,
		IsWebPage:   request.IsWebPage,
		IsNewTab:    request.IsNewTab,
		IsFull:      request.IsFull,
		HideMenu:    request.HideMenu,
		WebUrl:      request.WebUrl,
	}

	updateFields := []string{"status", "code", "title", "parent_id", "menu_path", "menu_icon", "type", "component", "description", "is_web_page", "is_new_tab", "is_full", "hide_menu", "web_url"}
	if err := impl.DBService.Model(&models.MgtPermission{}).Where("id = ?", request.ID).Select(updateFields).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})
}
