import "reflect-metadata";
import { config } from "dotenv";
import { AppDataSource } from "../data-source";
import { Page } from "../content/entities/page.entity";
import { ContentBlock } from "../content/entities/content-block.entity";
import { ALL_PAGES } from "./seed-content/index";

config();

// Seeds every page's content blocks to match that page's own hardcoded
// defaults exactly (see each file under ./seed-content/) — seeding never
// changes what's visible, it just gives the admin editor
// (/admin/dashboard/content) something to start from. Re-running this is
// always safe: it upserts by (page slug, block key) instead of duplicating.
async function main() {
  const dataSource = await AppDataSource.initialize();
  const pages = dataSource.getRepository(Page);
  const blocks = dataSource.getRepository(ContentBlock);

  for (const seedPage of ALL_PAGES) {
    let page = await pages.findOne({ where: { slug: seedPage.slug } });
    if (!page) {
      page = await pages.save(pages.create({ slug: seedPage.slug, title: seedPage.title }));
      console.log(`Created page: ${seedPage.slug}`);
    }

    const existing = await blocks.find({ where: { pageId: page.id } });
    const byKey = new Map(existing.map((b) => [b.key, b]));

    for (let i = 0; i < seedPage.blocks.length; i++) {
      const b = seedPage.blocks[i];
      const current = byKey.get(b.key);
      if (current) {
        current.label = b.label;
        current.sortOrder = i;
        current.type = b.type;
        await blocks.save(current);
      } else {
        await blocks.save(
          blocks.create({
            pageId: page.id,
            key: b.key,
            label: b.label,
            type: b.type,
            sortOrder: i,
            textValue: b.type === "image" ? null : b.value,
            imageUrl: b.type === "image" ? b.value : null,
          }),
        );
      }
    }

    console.log(`Seeded ${seedPage.blocks.length} content blocks for "${seedPage.slug}".`);
  }

  await dataSource.destroy();
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
