package permission

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

func Create(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
	}

	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
	}

	db := models.DBService.Model(&models.MgtPermission{})
	if err = db.Where("code = ? AND app_id = ?", request.Code, appId).First(&data).Error; err != nil {
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			infra.Response.Error(c, errcode.ErrDB)
			return
		}
		var deletedData models.MgtPermission
		if err = models.DBService.Unscoped().Where("code = ? AND app_id = ?", request.Code, appId).First(&deletedData).Error; err == nil {
			if err = models.DBService.Unscoped().Delete(&deletedData).Error; err != nil {
				infra.Response.Error(c, errcode.ErrDB)
				return
			}
		}
	} else {
		infra.Response.Error(c, errcode.ErrAlreadyExists)
		return
	}

	var dataModel = models.MgtPermission{
		Std_IICUDS:  coreTypes.Std_IICUDS{Identity: coreutils.UUID(), Status: 1},
		Code:        request.Code,
		Title:       request.Title,
		TitleEn:     request.TitleEn,
		Description: request.Description,
		Appid:       appId,
		ParentID:    request.ParentID,
		MenuPath:    request.MenuPath,
		MenuIcon:    request.MenuIcon,
		Type:        request.Type,
		Component:   request.Component,
		IsWebPage:   request.IsWebPage,
		IsNewTab:    request.IsNewTab,
		IsFull:      request.IsFull,
		HideMenu:    request.HideMenu,
		WebUrl:      request.WebUrl,
	}
	if err = models.DBService.Model(&models.MgtPermission{}).Create(&dataModel).Error; err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

	infra.Response.Success(c, types.IdResp{Id: dataModel.ID, Identity: dataModel.Identity})
}
