"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateAuthGuard = generateAuthGuard;
const Generator = __importStar(require("@postxl/generator"));
function generateAuthGuard(context) {
    const imports = Generator.ImportGenerator.from(context.authentication.guard._filePath);
    imports.add(context.view.service);
    imports.add(context.actions.dispatcher);
    imports.add(context.types.user);
    imports.add({ name: context.authentication.service.name, location: context.authentication.service._filePath });
    return /* ts */ `
  import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'

import { FastifyRequest } from 'fastify'

${imports.generate()}

import { UserInfo, UserRoles } from './authentication.types'

export type Viewer = { userInfo: UserInfo; userRoles: UserRoles; user: User; isAuthorized: boolean }

export type FastifyRequestWithViewer = FastifyRequest & { viewer: Viewer }
@Injectable()
export class ${context.authentication.guard.name} implements CanActivate {
  constructor(
    private readonly authService: ${context.authentication.service.name},
    private readonly viewService: ${context.view.service.name},
    private readonly dispatcherService: ${context.actions.dispatcher.name},
  ) {}

  public async canActivate(context: ExecutionContext): Promise<boolean> {
    const http = context.switchToHttp()
    const req = http.getRequest<FastifyRequestWithViewer>()

    let viewer: Viewer | null = null

    let userInfo: UserInfo | null = null
    let userRoles: UserRoles = []

    // TODO: Add authorization check
    const isAuthorized = true

    const associatedUserInfo = await this.authService.getUserInfoFromRequest(req)

    if (associatedUserInfo.ok) {
      userInfo = associatedUserInfo.userInfo
    }

    const associatedUserRoles = await this.authService.getUserRolesFromRequest(req)

    if (associatedUserRoles.ok) {
      userRoles = associatedUserRoles.userRoles
    }

    if (userInfo) {
      let user = await this.viewService.users.data.getBySub(userInfo.sub)

      if (!user) {
        // If user doesn't exist yet, we create a new one using the data in viewer
        // (i.e. provided by the authentication provider).
        user = await this.dispatcherService.dispatch({
          action: {
            scope: 'user',
            type: 'create',
            payload: { sub: userInfo.sub, name: userInfo.name, email: userInfo.email, profilePictureUrl: null },
          },
          user: this.viewService.users.data.rootUser,
        })

        if (!user) {
          throw new Error('Error creating new user!')
        }
      }

      viewer = { userInfo, userRoles, user, isAuthorized }
    }

    if (!viewer) {
      return false
    }

    req.viewer = viewer

    return true
  }
}`;
}
//# sourceMappingURL=auth-guard.generator.js.map