"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.groupAndSortModelsBySchema = groupAndSortModelsBySchema;
exports.generatePage = generatePage;
const node_path_1 = require("node:path");
const Generator = __importStar(require("@postxl/generator"));
/**
 * Groups models by their database schema and sorts both schemas and models alphabetically.
 *
 * @param context - The context containing all models
 * @returns An object containing sorted schemas and a map of models grouped by schema
 */
function groupAndSortModelsBySchema(context) {
    // Group models by schema
    const modelsBySchema = new Map();
    for (const model of context.models.values()) {
        const schema = model.databaseSchema;
        if (!modelsBySchema.has(schema)) {
            modelsBySchema.set(schema, []);
        }
        modelsBySchema.get(schema).push({
            name: model.name,
            route: model.admin.page.route,
            userFriendlyName: model.userFriendlyName,
        });
    }
    // Sort schemas alphabetically
    const sortedSchemas = Array.from(modelsBySchema.keys()).sort((a, b) => a.localeCompare(b));
    // Sort models within each schema alphabetically by userFriendlyName
    for (const schema of sortedSchemas) {
        const models = modelsBySchema.get(schema);
        models.sort((a, b) => a.userFriendlyName.localeCompare(b.userFriendlyName));
    }
    return {
        schemas: sortedSchemas,
        modelsBySchema,
    };
}
function generatePage({ page, paths, vfs, content, }) {
    const componentFilePath = (0, node_path_1.join)(paths.pages, Generator.toLocalReactComponent(page.pageComponent));
    vfs.write(componentFilePath, content);
    if (page.isOutlet) {
        vfs.write((0, node_path_1.join)(paths.routes, `${page.route}/index.lazy.tsx`), generateRoute(page));
        vfs.write((0, node_path_1.join)(paths.routes, `${page.route}.lazy.tsx`), generateOutlet(page));
        return;
    }
    vfs.write((0, node_path_1.join)(paths.routes, `${page.route}.lazy.tsx`), generateRoute(page));
    for (const alias of page.aliases ?? []) {
        vfs.write((0, node_path_1.join)(paths.routes, `${alias}.tsx`), generateAliasRoute({ alias, page }));
    }
}
function joinRoutes(...parts) {
    return ['/', ...parts].join('/').replaceAll(/\/+/g, '/');
}
function generateOutlet({ pageComponent, route }) {
    if (!route.startsWith('/')) {
        throw new Error(`Route for page ${pageComponent.name} must start with '/': ${route}!`);
    }
    return `import { Outlet } from '@tanstack/react-router'
import { createLazyFileRoute } from '@tanstack/react-router'

/**
 * Outlet Route for ${pageComponent.name}
 */
export const Route = createLazyFileRoute('${joinRoutes('_auth-routes', route)}')({
  component: () => <Outlet />,
})`;
}
function generateRoute({ pageComponent, route }) {
    if (!route.startsWith('/')) {
        throw new Error(`Route for page ${pageComponent.name} must start with '/': ${route}!`);
    }
    return `import ${pageComponent.name} from '${pageComponent.location}'
import { createLazyFileRoute } from '@tanstack/react-router'

export const Route = createLazyFileRoute('${joinRoutes('_auth-routes', route)}')({
  component: ${pageComponent.name},
})`;
}
function generateAliasRoute({ alias, page }) {
    return `import { redirect, createFileRoute } from '@tanstack/react-router'

export const Route = createFileRoute('${joinRoutes('_auth-routes', alias)}')({
  beforeLoad: () => {
    throw redirect({ to: '${joinRoutes(page.route)}' })
  },
})`;
}
//# sourceMappingURL=utils.js.map