/**
 * Seed empty layout pointers for app pages (favorites, wishlist, stores, club, category).
 * Run: pnpm --filter web db:seed:app-pages
 * Requires: DATABASE_URL
 */

import { scriptOutput } from '../../lib/script-output.js';
import { eq } from 'drizzle-orm';
import { getDb } from '../client.js';
import { pageLayoutPointers } from '../schema.js';
import { createLivePointer } from '../queries/page-layout-pointers.js';
import { insertPageLayoutSeedRow } from '../queries/seed-page-layouts.js';
import { readSeedDatabaseUrl } from '../seed-cli-env.js';

// Deterministic UUIDs — namespace a000, range 1-5
const ROUTES = [
  { route: 'favorites', layoutId: '00000000-0000-4000-a000-000000000001' },
  { route: 'wishlist', layoutId: '00000000-0000-4000-a000-000000000002' },
  { route: 'stores', layoutId: '00000000-0000-4000-a000-000000000003' },
  { route: 'club', layoutId: '00000000-0000-4000-a000-000000000004' },
  { route: 'category', layoutId: '00000000-0000-4000-a000-000000000005' },
] as const;

const EMPTY_BODY = { mobile: [], desktop: [] };

async function main() {
  const DATABASE_URL = readSeedDatabaseUrl();

  const db = getDb({ DATABASE_URL });

  for (const { route, layoutId } of ROUTES) {
    scriptOutput(`Seeding: ${route}`);

    await insertPageLayoutSeedRow(db, {
      id: layoutId,
      page: route,
      body: EMPTY_BODY,
      note: 'Initial empty seed',
    });

    const existing = await db
      .select({ page: pageLayoutPointers.page })
      .from(pageLayoutPointers)
      .where(eq(pageLayoutPointers.page, route))
      .limit(1);

    if (existing.length === 0) {
      await createLivePointer(db, route, layoutId);
      scriptOutput(`  created pointer`);
    } else {
      scriptOutput(`  pointer already exists — skip`);
    }
  }

  scriptOutput(`\nSeeded ${ROUTES.length} app pages.`);
  process.exit(0);
}

main().catch((e) => {
  console.error('Seed failed:', e);
  process.exit(1);
});
