"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.generateAdminGlobalActions = generateAdminGlobalActions;
const Generator = __importStar(require("@postxl/generator"));
const utils_1 = require("../utils");
function generateAdminGlobalActions({ context }) {
    const imports = Generator.ImportGenerator.from(Generator.toFilePath('./admin-global-actions.tsx'))
        .addImport({ from: Generator.toPackageName('react'), items: [Generator.toFunctionName('useEffect')] })
        .addImport({
        from: Generator.toPackageName('@tanstack/react-router'),
        items: [Generator.toFunctionName('useNavigate')],
    })
        .addImport({
        from: Generator.toBackendModuleLocation('@app-actions/command-palette-action'),
        items: [Generator.toFunctionName('command'), Generator.toFunctionName('waitForNextFrame')],
    })
        .addImport({
        from: Generator.toBackendModuleLocation('@app-actions/command-palette-store'),
        items: [Generator.toFunctionName('useCommandPaletteActions')],
    })
        .addImport({
        from: Generator.toBackendModuleLocation('@lib/config'),
        items: [Generator.toConstantName('APP_CONFIG')],
    })
        .addImport({
        from: Generator.toBackendModuleLocation('@context-providers/auth-context-provider'),
        items: [Generator.toFunctionName('getAuthHeaders')],
    })
        .addImport({
        from: Generator.toBackendModuleLocation('@lib/excel-download'),
        items: [Generator.toFunctionName('downloadBlob'), Generator.toFunctionName('getFilenameFromContentDisposition')],
    });
    const { schemas: sortedSchemas, modelsBySchema } = (0, utils_1.groupAndSortModelsBySchema)(context);
    const createActions = sortedSchemas
        .map((schema) => {
        const models = (modelsBySchema.get(schema) ?? []).filter((model) => !model.isReadonly);
        return models
            .map((model) => {
            return `
            command({
              key: 'create-admin-${model.name.toLowerCase()}',
              visibility: 'visible',
              group: 'Create',
              label: 'Create new ${model.userFriendlyName}',
              keywords: ['create', 'new', '${model.name.toLowerCase()}', '${model.userFriendlyName.toLowerCase()}'],
              run: async () => {
                if (typeof globalThis !== 'undefined') {
                  globalThis.sessionStorage.setItem('pxl:create-intent-model', '${model.name}')
                  globalThis.dispatchEvent(new CustomEvent('pxl:create-intent', { detail: { model: '${model.name}' } }))
                }
                await navigate({ to: '${model.route}' })
                await waitForNextFrame()
                return { kind: 'close' }
              },
            })
          `;
        })
            .join(',\n');
    })
        .join(',\n');
    const modelActions = sortedSchemas
        .map((schema) => {
        const models = modelsBySchema.get(schema) ?? [];
        return models
            .map((model) => {
            return `
            command({
              key: 'navigate-admin-${model.name.toLowerCase()}',
              visibility: 'visible',
              group: 'Navigate',
              label: 'Admin: ${model.userFriendlyName}',
              keywords: ['admin', '${model.name.toLowerCase()}', '${model.userFriendlyName.toLowerCase()}'],
              run: async () => {
                await navigate({ to: '${model.route}' })
                await waitForNextFrame()
                return { kind: 'close' }
              },
            })
          `;
        })
            .join(',\n');
    })
        .join(',\n');
    const exportActions = sortedSchemas
        .map((schema) => {
        const models = modelsBySchema.get(schema) ?? [];
        return models
            .map((model) => {
            const endpoint = model.route.split('/').findLast(Boolean) ?? model.name.toLowerCase();
            const fallbackFilename = `${endpoint}.xlsx`;
            return `
            command({
              key: 'export-admin-${model.name.toLowerCase()}-excel',
              visibility: 'visible',
              group: 'Export',
              label: 'Export: ${model.userFriendlyName} (Excel)',
              keywords: ['export', 'excel', '${model.name.toLowerCase()}', '${model.userFriendlyName.toLowerCase()}'],
              run: async () => {
                await downloadFromExcelIo('export/${endpoint}', '${fallbackFilename}')
                await waitForNextFrame()
                return { kind: 'close' }
              },
            })
          `;
        })
            .join(',\n');
    })
        .join(',\n');
    const dynamicActions = [createActions, modelActions].filter((value) => value.trim().length > 0).join(',\n');
    const adminDynamicActions = [exportActions].filter((value) => value.trim().length > 0).join(',\n');
    return `
${imports.generate()}

export const useAdminGlobalActions = () => {
  const navigate = useNavigate()
  const { registerGlobalActions } = useCommandPaletteActions()

  useEffect(() => {
    const downloadFromExcelIo = async (endpoint: string, fallbackFilename: string) => {
      const response = await fetch(\`${'${APP_CONFIG.apiURL}'}/excel-io/${'${endpoint}'}\`, {
        headers: getAuthHeaders(),
        credentials: 'include',
      })

      if (!response.ok) {
        throw new Error(\`Request failed with status ${'${response.status}'}\`)
      }

      const blob = await response.blob()
      const filename = getFilenameFromContentDisposition(response.headers.get('Content-Disposition'), fallbackFilename)
      downloadBlob(blob, filename)
    }

    const actions = [
      command({
        key: 'navigate-admin-overview',
        visibility: 'visible',
        group: 'Navigate',
        label: 'Admin: Overview',
        keywords: ['admin', 'overview'],
        run: async () => {
          await navigate({ to: '/admin' })
          await waitForNextFrame()
          return { kind: 'close' }
        },
      }),
      ${dynamicActions}
    ]

    if (import.meta.env.VITE_PUBLIC_ALLOW_ADMIN === 'true') {
      actions.push(
        command({
          key: 'navigate-admin-data-management',
          visibility: 'visible',
          group: 'Navigate',
          label: 'Admin: Data Management',
          keywords: ['admin', 'data', 'management'],
          run: async () => {
            await navigate({ to: '/admin/data-management' })
            await waitForNextFrame()
            return { kind: 'close' }
          },
        }),
        command({
          key: 'navigate-admin-excel-io',
          visibility: 'visible',
          group: 'Navigate',
          label: 'Admin: Excel I/O',
          keywords: ['admin', 'import', 'export', 'excel'],
          run: async () => {
            await navigate({ to: '/admin/excel-io' })
            await waitForNextFrame()
            return { kind: 'close' }
          },
        }),
        command({
          key: 'export-admin-all-models-excel',
          visibility: 'visible',
          group: 'Export',
          label: 'Export: All models (Excel)',
          keywords: ['export', 'excel', 'all', 'models'],
          run: async () => {
            await downloadFromExcelIo('export/all', 'all-models.xlsx')
            await waitForNextFrame()
            return { kind: 'close' }
          },
        }),
        ${adminDynamicActions}
      )
    }

    registerGlobalActions(...actions)
  }, [navigate, registerGlobalActions])
}
`;
}
//# sourceMappingURL=admin-global-actions.generator.js.map