#!/usr/bin/env tsx

/**
 * Re-export landing pages that are marked as published but missing their HTML override files.
 * This script fetches each page and triggers an update to regenerate the exports.
 */

import { prisma } from '../src/config/database';
import { pagesService } from '../src/modules/pages/pages.service';
import { logger } from '../src/utils/logger';

async function reexportPages() {
  try {
    // Find pages that are published but might be missing exports
    const pages = await prisma.landingPage.findMany({
      where: {
        published: true,
        mkdocsPath: { not: null },
      },
      select: {
        id: true,
        slug: true,
        title: true,
        description: true,
        editorMode: true,
        blocks: true,
        htmlOutput: true,
        cssOutput: true,
        mkdocsPath: true,
        mkdocsExportMode: true,
        mkdocsHideNav: true,
        mkdocsHideToc: true,
        published: true,
        seoTitle: true,
        seoDescription: true,
      },
    });

    logger.info(`Found ${pages.length} published pages with mkdocsPath set`);

    for (const page of pages) {
      logger.info(`Re-exporting page: ${page.slug} (${page.id})`);

      try {
        // Trigger update with same data - this will re-export the page
        await pagesService.update(page.id, {
          title: page.title,
          description: page.description ?? undefined,
          editorMode: page.editorMode,
          blocks: page.blocks,
          htmlOutput: page.htmlOutput ?? undefined,
          cssOutput: page.cssOutput ?? undefined,
          mkdocsPath: page.mkdocsPath ?? undefined,
          mkdocsExportMode: page.mkdocsExportMode,
          mkdocsHideNav: page.mkdocsHideNav,
          mkdocsHideToc: page.mkdocsHideToc,
          published: true,
          seoTitle: page.seoTitle ?? undefined,
          seoDescription: page.seoDescription ?? undefined,
        });

        logger.info(`✓ Successfully re-exported ${page.slug}`);
      } catch (err) {
        logger.error(`✗ Failed to re-export ${page.slug}:`, err);
      }
    }

    logger.info('Re-export complete');
  } catch (err) {
    logger.error('Re-export script failed:', err);
    throw err;
  } finally {
    await prisma.$disconnect();
  }
}

reexportPages().catch((err) => {
  console.error('Fatal error:', err);
  process.exit(1);
});
