package permission

import (
	"context"

	"gateway/internal/model/permission/domain/enum"
	domperm "gateway/internal/model/permission/domain/usecase"
	"gateway/internal/svc"
	"gateway/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

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

// NewCreateRoleLogic returns the create-role logic.
func NewCreateRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateRoleLogic {
	return &CreateRoleLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// CreateRole inserts a new tenant-scoped role.
func (l *CreateRoleLogic) CreateRole(req *types.CreateRoleReq) (*types.RoleData, error) {
	if l.svcCtx.PermissionRole == nil {
		return nil, errb.SysNotImplemented("permission module not configured")
	}
	actor, err := ActorFromContext(l.ctx)
	if err != nil {
		return nil, errb.AuthUnauthorized(err.Error()).WithCause(err)
	}
	role, err := l.svcCtx.PermissionRole.Create(l.ctx, &domperm.CreateRoleParam{
		TenantID:    actor.TenantID,
		Key:         req.Key,
		DisplayName: req.DisplayName,
		CreatorUID:  actor.UID,
		Status:      enum.Status(req.Status),
	})
	if err != nil {
		return nil, err
	}
	return &types.RoleData{
		ID:          role.ID.Hex(),
		TenantID:    role.TenantID,
		Key:         role.Key,
		DisplayName: role.DisplayName,
		CreatorUID:  role.CreatorUID,
		Status:      role.Status.String(),
		IsSystem:    role.IsSystem,
		CreateAt:    role.CreateAt,
		UpdateAt:    role.UpdateAt,
	}, nil
}
