"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.generator = exports.generatorId = void 0;
const node_path_1 = require("node:path");
const Generator = __importStar(require("@postxl/generator"));
const backend_actions_1 = require("../backend-actions");
const backend_core_1 = require("../backend-core");
const backend_view_1 = require("../backend-view");
const base_1 = require("../base");
const auth_guard_generator_1 = require("./generators/auth-guard.generator");
const authentication_module_generator_1 = require("./generators/authentication-module.generator");
const authentication_service_generator_1 = require("./generators/authentication-service.generator");
const authentication_types_generator_1 = require("./generators/authentication-types.generator");
exports.generatorId = Generator.toGeneratorInterfaceId('backend-authentication');
exports.generator = {
    id: exports.generatorId,
    requires: [backend_core_1.backendGeneratorId, base_1.baseGeneratorId, backend_view_1.backendViewGeneratorId, backend_actions_1.backendActionsGeneratorId],
    register: (context) => {
        context.backend.packageJson.devDependencies.push({ packageName: '@types/jsonwebtoken', version: '9.0.10' });
        context.backend.packageJson.dependencies.push({ packageName: '@fastify/cookie', version: '11.0.2' }, { packageName: '@fastify/cors', version: '11.2.0' }, { packageName: '@fastify/helmet', version: '13.0.2' }, { packageName: 'jsonwebtoken', version: '9.0.3' }, { packageName: 'oidc-client-ts', version: '3.4.1' });
        const module = {
            name: Generator.toClassName('AuthenticationModule'),
            location: Generator.toBackendModuleLocation(`@authentication/authentication.module`),
            _filePath: Generator.toFilePath('./authentication.module'),
        };
        const authenticationModule = {
            name: Generator.toBackendModuleName('authentication'),
            moduleClass: module,
            apiModuleRegistration: {
                code: Generator.ts(`AuthenticationModule.forRoot(config.auth)`),
            },
            envConfig: {
                decoder: Generator.ts(`
          AUTH: zEnvBoolean.optional().default(true),
          KEYCLOAK_URL: z.string().url().transform((val) => new URL(val)),
          KEYCLOAK_CLIENT_ID: z.string(),
          KEYCLOAK_CLIENT_SECRET: z.string(),
          KEYCLOAK_REALM: z.string(),
          KEYCLOAK_REDIRECT_URL: z.string().url().transform((val) => new URL(val)),
          KEYCLOAK_LOGOUT_REDIRECT_URL: z.string().url().transform((val) => new URL(val)),`),
                transformer: Generator.ts(`
          auth: val.AUTH ? {
            enableAuthentication: true as const,
            url: val.API_URL,
            urlPrefix: val.API_PREFIX,
            
            frontendUrl: val.FRONTEND_URL,
            
            clientId: val.KEYCLOAK_CLIENT_ID,
            clientSecret: val.KEYCLOAK_CLIENT_SECRET,
            
            realm: val.KEYCLOAK_REALM,
            keycloakUrl: val.KEYCLOAK_URL,
            redirectUrl: val.KEYCLOAK_REDIRECT_URL,
            
            postLogoutRedirectUrl: val.KEYCLOAK_LOGOUT_REDIRECT_URL,
          } : {
            enableAuthentication: false as const,
          }`),
                dotEnvExample: `
          KEYCLOAK_URL=http://localhost:8080
          KEYCLOAK_CLIENT_ID=development
          KEYCLOAK_CLIENT_SECRET="secret"
          KEYCLOAK_REALM=postxl
          KEYCLOAK_REDIRECT_URL=\${API_URL}/auth/callback
          KEYCLOAK_LOGOUT_REDIRECT_URL=\${FRONTEND_URL}
          `,
            },
        };
        context.backend.modules.push(authenticationModule);
        const service = {
            name: Generator.toClassName('AuthenticationService'),
            location: Generator.toBackendModuleLocation('@authentication/authentication.service'),
            _filePath: Generator.toFilePath('./authentication.service.ts'),
        };
        const guard = {
            name: Generator.toClassName('AuthGuard'),
            location: Generator.toBackendModuleLocation('@authentication/auth.guard'),
            _filePath: Generator.toFilePath('./auth.guard.ts'),
        };
        const authenticationContext = {
            module,
            service,
            guard,
            types: {
                userInfo: {
                    name: Generator.toTypeName('UserInfo'),
                    location: Generator.toBackendModuleLocation('@authentication/authentication.types'),
                },
                userRoles: {
                    name: Generator.toTypeName('UserRoles'),
                    location: Generator.toBackendModuleLocation('@authentication/authentication.types'),
                },
            },
        };
        return { ...context, authentication: authenticationContext };
    },
    generate: async (context) => {
        const vfsSrc = new Generator.VirtualFileSystem();
        vfsSrc.write(Generator.toLocalFile(context.authentication.module), (0, authentication_module_generator_1.generateAuthenticationModule)(context));
        vfsSrc.write(context.authentication.guard._filePath, (0, auth_guard_generator_1.generateAuthGuard)(context));
        vfsSrc.write(context.authentication.service._filePath, (0, authentication_service_generator_1.generateAuthenticationService)(context));
        vfsSrc.write(Generator.toLocalFile(context.authentication.types.userInfo), (0, authentication_types_generator_1.generateAuthenticationTypes)(context));
        const vfs = new Generator.VirtualFileSystem();
        vfs.insertFromVfs({ vfs: vfsSrc, targetPath: 'src' });
        await vfs.loadFolder({ diskPath: (0, node_path_1.resolve)(__dirname, './template') });
        vfs.write('/tsconfig.lib.json', Generator.generateTsConfig('authentication'));
        context.vfs.insertFromVfs({ targetPath: 'backend/libs/authentication', vfs });
        return context;
    },
};
//# sourceMappingURL=authentication.generator.js.map