package role

import (
	"context"
	"git.noahlan.cn/n-admin/n-admin-server/dal/errx"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent/role"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/internal/utils/entx"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/internal/utils/hander"
	"git.noahlan.cn/noahlan/ntool-biz/core/nstatus"
	"git.noahlan.cn/noahlan/ntool-biz/core/nstatus/code"
	"git.noahlan.cn/noahlan/ntool-biz/core/nstatus/msg"
	"git.noahlan.cn/noahlan/ntool-biz/core/orm/nent/types"

	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/internal/svc"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/types/core"
)

type CreateRoleLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateRoleLogic {
	return &CreateRoleLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// Role management
func (l *CreateRoleLogic) CreateRole(in *core.RoleInfo) (*core.BaseIDResp, error) {
	var id int64
	if err := entx.WithTx(l.ctx, l.svcCtx.DB, func(tx *ent.Tx) error {
		if err := l.preCheck(tx, in); err != nil {
			return err
		}

		dbData, err := tx.Role.Create().
			SetStatus(types.ParseStatus(in.Status)).
			SetName(in.Name).
			SetCode(in.Code).
			SetDescription(in.Description).
			Save(l.ctx)
		if err != nil {
			return hander.HandleEntErr(err, in)
		}
		id = dbData.ID

		return nil
	}); err != nil {
		return nil, err
	}

	return &core.BaseIDResp{
		ID:   id,
		Code: code.StatusOK,
		Msg:  msg.CreateSuccess,
	}, nil
}

func (l *CreateRoleLogic) preCheck(tx *ent.Tx, in *core.RoleInfo) error {
	if in.Code == "" {
		return nstatus.NewBizErrWithCode(errx.RoleCodeNotEmpty)
	}
	// check exists
	exist, err := tx.Role.Query().Where(role.CodeEQ(in.Code)).Exist(l.ctx)
	if err != nil {
		return hander.HandleEntErr(err, in)
	}
	if exist {
		return nstatus.NewBizErrWithCode(errx.RoleCodeInUsed)
	}
	return nil
}
