package permission

import (
	"context"

	"gateway/internal/svc"
	"gateway/internal/types"

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

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

// NewReplaceRolePermissionsLogic returns the bulk-replace logic.
func NewReplaceRolePermissionsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ReplaceRolePermissionsLogic {
	return &ReplaceRolePermissionsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// ReplaceRolePermissions atomically rewrites the role's permission set.
// Parents of every requested leaf are auto-included by the usecase.
func (l *ReplaceRolePermissionsLogic) ReplaceRolePermissions(req *types.ReplaceRolePermissionsByIDReq) error {
	if l.svcCtx.PermissionRolePermission == nil {
		return errb.SysNotImplemented("permission module not configured")
	}
	actor, err := ActorFromContext(l.ctx)
	if err != nil {
		return errb.AuthUnauthorized(err.Error()).WithCause(err)
	}
	return l.svcCtx.PermissionRolePermission.Replace(l.ctx, actor.TenantID, req.ID, req.PermissionIDs)
}
