"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateAuthorizationService = generateAuthorizationService;
const generator_1 = require("@postxl/generator");
function generateAuthorizationService({ actions, types, schema }) {
    const imports = generator_1.ImportGenerator.from(actions.authorization.service.location)
        .add(actions.authorization.policy)
        .addType(actions.summary.action)
        .addType(types.authorizationContext)
        .addType(actions.execution.interface);
    return /* ts */ `
import { Injectable, Logger } from '@nestjs/common'

${imports.generate()}

type AuthorizeActionContext = AuthorizationContext & {
  action: Action
  execution: IActionExecution
}

@Injectable()
export class ${actions.authorization.service.name} {
  private readonly _logger = new Logger(${actions.authorization.service.name}.name)
  private static readonly SYSTEM_USER_ID = ${JSON.stringify(schema.systemUser.id ?? 'root')}

  constructor(private readonly authorizationPolicyService: ${actions.authorization.policy.name}) {}

  public authorizeAction({ action, user, userRoles, execution: _execution }: AuthorizeActionContext): boolean {
    if (user.id === ${actions.authorization.service.name}.SYSTEM_USER_ID) {
      return true
    }

    const isAllowed = this.authorizationPolicyService.canRunAction({
      authorization: { user, userRoles },
      scope: action.scope,
      actionType: action.type,
    })
    if (!isAllowed) {
      this._logger.warn(\`Authorization denied for action scope/type "\${action.scope}.\${action.type}".\`)
    }
    return isAllowed
  }

}
`;
}
//# sourceMappingURL=authorization-service.generator.js.map