"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 Generator = __importStar(require("@postxl/generator"));
const backend_router_trpc_1 = require("../backend-router-trpc");
const backend_update_1 = require("../backend-update");
const base_1 = require("../base");
const frontend_core_1 = require("../frontend-core");
const types_1 = require("../types");
const model_hook_generator_1 = require("./generators/model-hook.generator");
const trpc_client_generator_1 = require("./generators/trpc-client.generator");
exports.generatorId = Generator.toGeneratorInterfaceId('frontend-trpc-client');
exports.generator = {
    id: exports.generatorId,
    requires: [
        base_1.baseGeneratorId,
        types_1.typesGeneratorId,
        frontend_core_1.frontendGeneratorId,
        backend_router_trpc_1.backendTrpcRouterGeneratorId,
        backend_update_1.backendUpdateGeneratorId,
    ],
    register: (context) => {
        const { packageVersions } = context.trpcRouter;
        context.frontend.packageJson.dependencies.push({ packageName: '@tanstack/react-query-devtools', version: '5.91.1' }, { packageName: '@tanstack/react-query', version: '5.90.12' }, { packageName: '@trpc/client', version: packageVersions.trpc }, { packageName: '@trpc/react-query', version: packageVersions.trpc }, { packageName: '@trpc/tanstack-react-query', version: packageVersions.trpc }, { packageName: 'react-query', version: '3.39.3' }, { packageName: 'superjson', version: packageVersions.superJSON });
        const location = Generator.toBackendModuleLocation('@lib/trpc');
        const trpcClient = {
            // Important: Do not change this name as this is the default name as provided by the TRPC library
            name: Generator.toConstantName('useTRPC'),
            location,
        };
        const models = new Map();
        for (const [modelName, model] of context.models) {
            models.set(modelName, registerModel(model));
        }
        return {
            ...context,
            trpcClient,
            models,
        };
    },
    afterRegistrations: (context) => {
        for (const backendModule of context.backend.modules) {
            context.frontend.tsConfigReferences.set(backendModule.name, {
                name: backendModule.name,
                filePath: Generator.toFilePath(`../../backend/libs/${backendModule.name}/src`),
                hasIndex: backendModule.hasIndex ?? false,
            });
        }
    },
    generate: async (context) => {
        const contextVfs = new Generator.VirtualFileSystem();
        for (const model of context.models.values()) {
            await contextVfs.write(Generator.toLocalReactComponent(model.itemHook), (0, model_hook_generator_1.generateModelHook)({ model, context }));
        }
        context.vfs.insertFromVfs({ targetPath: 'frontend/src/hooks/', vfs: contextVfs });
        context.vfs.write('frontend/src/lib/trpc.ts', (0, trpc_client_generator_1.generateTrpcClient)(context));
        return Promise.resolve(context); // NOSONAR
    },
};
function registerModel(model) {
    const location = Generator.toBackendModuleLocation(`@hooks/use-${model._conjugated.kebabCasePlural}`);
    return {
        ...model,
        itemHook: { name: Generator.toConstantName(`use${model._conjugated.PascalCase}`), location },
        itemsHook: {
            name: Generator.toConstantName(`use${model._conjugated.PascalCasePlural}`),
            location,
            type: { name: Generator.toTypeName(`${model._conjugated.PascalCasePlural}Hook`), location },
            list: { name: Generator.toConstantName(`list`), location },
            map: { name: Generator.toConstantName(`map`), location },
            isLoaded: { name: Generator.toConstantName(`isLoaded`), location },
            filteredList: { name: Generator.toConstantName(`filteredList`), location },
            filteredMap: { name: Generator.toConstantName(`filteredMap`), location },
            ...(model.update.kind === 'exists'
                ? {
                    create: { name: Generator.toConstantName(`create`), location },
                    createMany: { name: Generator.toConstantName(`createMany`), location },
                    update: { name: Generator.toConstantName(`update`), location },
                    updateMany: { name: Generator.toConstantName(`updateMany`), location },
                    updateField: { name: Generator.toConstantName(`updateField`), location },
                    delete: { name: Generator.toConstantName(`delete`), location },
                    deleteMany: { name: Generator.toConstantName(`deleteMany`), location },
                    clone: { name: Generator.toConstantName(`clone`), location },
                    cloneMany: { name: Generator.toConstantName(`cloneMany`), location },
                }
                : {}),
        },
    };
}
//# sourceMappingURL=trpc-client.generator.js.map