import { PrismaClient, RegionType, PublishStatus, IndexStatus } from "@prisma/client";
import bcrypt from "bcryptjs";
import { jatengRegions, semarangDistricts, slugify } from "../lib/regions";
import { seoArticles } from "../lib/articles";
import { districtContent, jatengEditorial, villageEditorial } from "../lib/local-content";
import { site } from "../lib/site";

const prisma = new PrismaClient();

function articleHtml(article: (typeof seoArticles)[number]) {
  return [
    `<p>${article.excerpt}</p>`,
    ...article.sections.map(section => [
      `<h2>${section.heading}</h2>`,
      ...section.paragraphs.map(p => `<p>${p}</p>`),
      section.bullets?.length ? `<ul>${section.bullets.map(b => `<li>${b}</li>`).join("")}</ul>` : "",
    ].join("\n")),
  ].join("\n");
}

async function main() {
  const email = process.env.ADMIN_EMAIL || "admin@aljannah.org";
  const pass = process.env.ADMIN_PASSWORD || "CHANGE_ME";
  await prisma.user.upsert({
    where: { email },
    update: {},
    create: { name: "Administrator", email, passwordHash: await bcrypt.hash(pass, 12), role: "SUPER_ADMIN" },
  });

  let province = await prisma.region.findFirst({ where: { slug: "jawa-tengah", type: RegionType.PROVINCE } });
  if (!province) province = await prisma.region.create({ data: { name: "Jawa Tengah", slug: "jawa-tengah", type: RegionType.PROVINCE } });

  for (const r of jatengRegions) {
    const regionType = r.type === "kota" ? RegionType.CITY : RegionType.REGENCY;
    const reg = await prisma.region.upsert({
      where: { type_slug_parentId: { type: regionType, slug: r.slug, parentId: province.id } },
      update: { name: r.name },
      create: { name: r.name, slug: r.slug, type: regionType, parentId: province.id },
    });

    if (r.slug === "kota-semarang") {
      for (const d of semarangDistricts) {
        const district = await prisma.region.upsert({
          where: { type_slug_parentId: { type: RegionType.DISTRICT, slug: d.slug, parentId: reg.id } },
          update: { name: d.name },
          create: { name: d.name, slug: d.slug, type: RegionType.DISTRICT, parentId: reg.id },
        });
        const dc = districtContent(d.slug);
        const districtUrl = `/panti-asuhan-semarang/${d.slug}`;
        await prisma.seoLandingPage.upsert({
          where: { slug: `semarang-${d.slug}` },
          update: {
            title: `Panti Asuhan di ${d.name}, Semarang`,
            intro: dc.intro,
            content: `<h2>Informasi Panti Asuhan ${d.name}</h2><p>${dc.intro}</p><p>Halaman ini membantu ${dc.audience}. Al Jannah beralamat di ${site.address}.</p><h2>Donasi Resmi Al Jannah</h2><p>BRI 136901000387306 a.n. Yayasan Al Jannah Semarang. BSI 7036542211 a.n. PA AL JANNAH.</p>`,
            focusKeyword: `panti asuhan ${d.name}`,
            seoTitle: `Panti Asuhan di ${d.name}, Semarang | Al Jannah`,
            metaDescription: `Informasi panti asuhan di Kecamatan ${d.name}, Semarang, halaman kelurahan, panduan donasi, program dan kontak resmi Al Jannah.`,
            canonicalUrl: `${site.url}${districtUrl}`,
            qualityScore: 94,
            indexable: true,
            status: PublishStatus.PUBLISHED,
            indexStatus: IndexStatus.UNKNOWN,
          },
          create: {
            regionId: district.id,
            title: `Panti Asuhan di ${d.name}, Semarang`,
            slug: `semarang-${d.slug}`,
            intro: dc.intro,
            content: `<h2>Informasi Panti Asuhan ${d.name}</h2><p>${dc.intro}</p><p>Halaman ini membantu ${dc.audience}. Al Jannah beralamat di ${site.address}.</p><h2>Donasi Resmi Al Jannah</h2><p>BRI 136901000387306 a.n. Yayasan Al Jannah Semarang. BSI 7036542211 a.n. PA AL JANNAH.</p>`,
            focusKeyword: `panti asuhan ${d.name}`,
            seoTitle: `Panti Asuhan di ${d.name}, Semarang | Al Jannah`,
            metaDescription: `Informasi panti asuhan di Kecamatan ${d.name}, Semarang, halaman kelurahan, panduan donasi, program dan kontak resmi Al Jannah.`,
            canonicalUrl: `${site.url}${districtUrl}`,
            qualityScore: 94,
            indexable: true,
            status: PublishStatus.PUBLISHED,
            indexStatus: IndexStatus.UNKNOWN,
          },
        });
        await prisma.keyword.upsert({
          where: { keyword: `panti asuhan ${d.name.toLowerCase()}` },
          update: { targetUrl: districtUrl, location: `${d.name}, Semarang`, searchIntent: "LOCAL_INFORMATIONAL" },
          create: { keyword: `panti asuhan ${d.name.toLowerCase()}`, targetUrl: districtUrl, location: `${d.name}, Semarang`, searchIntent: "LOCAL_INFORMATIONAL" },
        });

        for (const v of d.villages) {
          const villageSlug = slugify(v);
          const village = await prisma.region.upsert({
            where: { type_slug_parentId: { type: RegionType.VILLAGE, slug: villageSlug, parentId: district.id } },
            update: { name: v },
            create: { name: v, slug: villageSlug, type: RegionType.VILLAGE, parentId: district.id },
          });
          const vc = villageEditorial(v, d.name, d.slug);
          const villageUrl = `/panti-asuhan-semarang/${d.slug}/${villageSlug}`;
          const villageContent = `<h2>Mencari panti asuhan dari ${v}</h2><p>${vc.lead}</p><p>${vc.service}</p><h2>Program Al Jannah</h2><p>Pengasuhan, pendidikan, pembinaan keagamaan, dan kemandirian menjadi arah program Al Jannah Semarang.</p><h2>Panduan donasi</h2><p>${vc.guidance}</p><p>BRI 136901000387306 a.n. Yayasan Al Jannah Semarang. BSI 7036542211 a.n. PA AL JANNAH.</p><h2>Kontak</h2><p>WhatsApp ${site.whatsappDisplay}, telepon ${site.phone}, email ${site.email}.</p>`;
          await prisma.seoLandingPage.upsert({
            where: { slug: `semarang-${d.slug}-${villageSlug}` },
            update: {
              title: `Panti Asuhan di ${v}, ${d.name}, Semarang`, intro: vc.lead, content: villageContent,
              focusKeyword: `panti asuhan ${v}`, seoTitle: `Panti Asuhan di ${v}, ${d.name}, Semarang | Al Jannah`,
              metaDescription: `Informasi panti asuhan di Kelurahan ${v}, Kecamatan ${d.name}, Semarang, panduan donasi dan kontak resmi Al Jannah.`,
              canonicalUrl: `${site.url}${villageUrl}`, qualityScore: 93, indexable: true,
              status: PublishStatus.PUBLISHED, indexStatus: IndexStatus.UNKNOWN,
            },
            create: {
              regionId: village.id, title: `Panti Asuhan di ${v}, ${d.name}, Semarang`, slug: `semarang-${d.slug}-${villageSlug}`,
              intro: vc.lead, content: villageContent, focusKeyword: `panti asuhan ${v}`,
              seoTitle: `Panti Asuhan di ${v}, ${d.name}, Semarang | Al Jannah`,
              metaDescription: `Informasi panti asuhan di Kelurahan ${v}, Kecamatan ${d.name}, Semarang, panduan donasi dan kontak resmi Al Jannah.`,
              canonicalUrl: `${site.url}${villageUrl}`, qualityScore: 93, indexable: true,
              status: PublishStatus.PUBLISHED, indexStatus: IndexStatus.UNKNOWN,
            },
          });
          await prisma.keyword.upsert({
            where: { keyword: `panti asuhan ${v.toLowerCase()} ${d.name.toLowerCase()}` },
            update: { targetUrl: villageUrl, location: `${v}, ${d.name}, Semarang`, searchIntent: "LOCAL_INFORMATIONAL" },
            create: { keyword: `panti asuhan ${v.toLowerCase()} ${d.name.toLowerCase()}`, targetUrl: villageUrl, location: `${v}, ${d.name}, Semarang`, searchIntent: "LOCAL_INFORMATIONAL" },
          });
        }
      }
    } else {
      const simple = r.name.replace(/^Kabupaten |^Kota /, "");
      const ec = jatengEditorial(r.slug, r.name);
      const regionUrl = `/panti-asuhan-jawa-tengah/${r.slug}`;
      const content = `<h2>Mencari panti asuhan di ${r.name}</h2><p>${ec.lead}</p><p>${ec.verification}</p><h2>Hubungan dengan Al Jannah</h2><p>${ec.relation}</p><h2>Donasi ke Al Jannah</h2><p>BRI 136901000387306 a.n. Yayasan Al Jannah Semarang. BSI 7036542211 a.n. PA AL JANNAH. Verifikasi melalui WhatsApp ${site.whatsappDisplay}.</p>`;
      await prisma.seoLandingPage.upsert({
        where: { slug: `jateng-${r.slug}` },
        update: { title: `Panti Asuhan di ${simple}, Jawa Tengah`, intro: ec.lead, content, focusKeyword: `panti asuhan ${simple}`, seoTitle: `Panti Asuhan di ${simple}, Jawa Tengah | Al Jannah`, metaDescription: `Informasi panti asuhan di ${r.name}, panduan verifikasi lembaga, donasi anak yatim dan rujukan Al Jannah Semarang.`, canonicalUrl: `${site.url}${regionUrl}`, qualityScore: 90, indexable: true, status: PublishStatus.PUBLISHED, indexStatus: IndexStatus.UNKNOWN },
        create: { regionId: reg.id, title: `Panti Asuhan di ${simple}, Jawa Tengah`, slug: `jateng-${r.slug}`, intro: ec.lead, content, focusKeyword: `panti asuhan ${simple}`, seoTitle: `Panti Asuhan di ${simple}, Jawa Tengah | Al Jannah`, metaDescription: `Informasi panti asuhan di ${r.name}, panduan verifikasi lembaga, donasi anak yatim dan rujukan Al Jannah Semarang.`, canonicalUrl: `${site.url}${regionUrl}`, qualityScore: 90, indexable: true, status: PublishStatus.PUBLISHED, indexStatus: IndexStatus.UNKNOWN },
      });
      await prisma.keyword.upsert({
        where: { keyword: `panti asuhan ${simple.toLowerCase()} jawa tengah` },
        update: { targetUrl: regionUrl, location: `${r.name}, Jawa Tengah`, searchIntent: "LOCAL_INFORMATIONAL" },
        create: { keyword: `panti asuhan ${simple.toLowerCase()} jawa tengah`, targetUrl: regionUrl, location: `${r.name}, Jawa Tengah`, searchIntent: "LOCAL_INFORMATIONAL" },
      });
    }
  }

  for (let index = 0; index < seoArticles.length; index++) {
    const article = seoArticles[index];
    const publishedAt = new Date(Date.UTC(2026, 7, Math.max(1, 26 - index)));
    await prisma.article.upsert({
      where: { slug: article.slug },
      update: {
        title: article.title, excerpt: article.excerpt, content: articleHtml(article), focusKeyword: article.focusKeyword,
        supportingKeywords: article.supportingKeywords, seoTitle: article.title, metaDescription: article.excerpt,
        canonicalUrl: `${site.url}/artikel/${article.slug}`, status: PublishStatus.PUBLISHED, robotsIndex: true, robotsFollow: true, seoScore: 94, publishedAt,
      },
      create: {
        title: article.title, slug: article.slug, excerpt: article.excerpt, content: articleHtml(article), focusKeyword: article.focusKeyword,
        supportingKeywords: article.supportingKeywords, seoTitle: article.title, metaDescription: article.excerpt,
        canonicalUrl: `${site.url}/artikel/${article.slug}`, status: PublishStatus.PUBLISHED, robotsIndex: true, robotsFollow: true, seoScore: 94, publishedAt,
      },
    });
    await prisma.keyword.upsert({
      where: { keyword: article.focusKeyword.toLowerCase() },
      update: { targetUrl: `/artikel/${article.slug}`, searchIntent: "INFORMATIONAL", location: "Semarang, Jawa Tengah" },
      create: { keyword: article.focusKeyword.toLowerCase(), targetUrl: `/artikel/${article.slug}`, searchIntent: "INFORMATIONAL", location: "Semarang, Jawa Tengah" },
    });
  }

  console.log(`Seed selesai: ${seoArticles.length} artikel SEO + halaman SEO wilayah Jawa Tengah/Semarang.`);
}

main().finally(() => prisma.$disconnect());
