"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.databaseGeneratorId = exports.generatorId = void 0;
const node_path_1 = require("node:path");
const Generator = __importStar(require("@postxl/generator"));
const generator_1 = require("@postxl/generator");
const backend_core_1 = require("../backend-core");
const base_1 = require("../base");
const database_config_generator_1 = require("./generators/database-config.generator");
const database_module_generator_1 = require("./generators/database-module.generator");
const database_service_generator_1 = require("./generators/database-service.generator");
const index_generator_1 = require("./generators/index.generator");
const prisma_schema_generator_1 = require("./generators/prisma-schema.generator");
exports.generatorId = Generator.toGeneratorInterfaceId('backend-database-prisma');
exports.databaseGeneratorId = Generator.toGeneratorInterfaceId('backend-database');
exports.generator = {
    id: exports.generatorId,
    implementsInterface: [exports.databaseGeneratorId],
    requires: [backend_core_1.backendGeneratorId, base_1.baseGeneratorId],
    register: (context) => {
        const moduleClass = {
            name: Generator.toClassName('DatabaseModule'),
            location: Generator.toBackendModuleLocation('@database/database.module'),
        };
        const module = {
            name: Generator.toBackendModuleName('database'),
            moduleClass,
            apiModuleRegistration: {
                code: (0, generator_1.ts)(`
        DatabaseModule.forRoot(config.db)`),
            },
            envConfig: {
                dotEnvExample: `DATABASE_CONNECTION=postgresql://postgres:postgres@localhost:5432/${context.schema.slug}`, // NOSONAR - this is an example
                decoder: (0, generator_1.ts)('DATABASE_CONNECTION: z.string()'),
                transformer: (0, generator_1.ts)('db: { connectionString: val.DATABASE_CONNECTION }'),
            },
        };
        context.backend.modules.push(module);
        const version = '6.19.0';
        const adapterVersion = '6.19.0';
        const pgVersion = '8.13.1';
        const typesPgVersion = '8.15.6';
        context.base.packageJson.devDependencies.push({ packageName: 'prisma', version }, { packageName: '@prisma/client', version });
        context.base.packageJson.scripts.push({ name: 'generate:prisma', command: 'prisma generate' });
        // replace the generate script to also run prisma generate
        const generateScript = context.base.packageJson.scripts.find((s) => s.name === 'generate');
        if (generateScript) {
            generateScript.command += ' && pnpm run generate:prisma';
        }
        else {
            context.base.packageJson.scripts.push({ name: 'generate', command: 'pnpm run generate:prisma' });
        }
        context.backend.packageJson.dependencies.push({ packageName: '@prisma/client', version }, { packageName: '@prisma/adapter-pg', version: adapterVersion }, { packageName: 'pg', version: pgVersion });
        context.backend.packageJson.devDependencies.push({ packageName: '@types/pg', version: typesPgVersion });
        const configLocation = Generator.toBackendModuleLocation(`@database/database.config`);
        const config = {
            name: Generator.toClassName('DatabaseConfig'),
            location: configLocation,
            type: { name: Generator.toTypeName('Config'), location: configLocation },
        };
        const database = {
            module,
            prismaClient: {
                name: Generator.toClassName(`PrismaClient`),
                location: Generator.toBackendModuleLocation(`@database/prisma/client`),
            },
            databaseTypesLocation: Generator.toBackendModuleLocation(`@database`),
            service: {
                name: Generator.toClassName('DatabaseService'),
                location: Generator.toBackendModuleLocation(`@database/database.service`),
            },
            config,
        };
        return { ...context, database };
    },
    generate: async (context) => {
        const srcVfs = new Generator.VirtualFileSystem();
        srcVfs.write('schema.prisma', (0, prisma_schema_generator_1.generatePrismaSchema)(context));
        srcVfs.write(Generator.toLocalFile(context.database.module.moduleClass), (0, database_module_generator_1.generateDatabaseModule)(context.database)); // NOSONAR
        srcVfs.write(Generator.toLocalFile(context.database.service), (0, database_service_generator_1.generateDatabaseService)(context.database));
        srcVfs.write(Generator.toLocalFile(context.database.config), (0, database_config_generator_1.generateDatabaseConfig)(context.database));
        srcVfs.write('index.ts', (0, index_generator_1.generatePrismaIndex)(context.database));
        const moduleVfs = new Generator.VirtualFileSystem();
        moduleVfs.insertFromVfs({ targetPath: 'src', vfs: srcVfs });
        context.vfs.insertFromVfs({ targetPath: 'backend/libs/database', vfs: moduleVfs });
        await context.vfs.loadFolder({ diskPath: (0, node_path_1.resolve)(__dirname, 'template') });
        return context;
    },
};
//# sourceMappingURL=prisma.generator.js.map