// src/lib/db/seed.ts
// Dev seed (resets domain data): demo org + owner, sites (with url/langs/country),
// the global link_sources directory, keywords, and a few example prospects.
// Run: bun run db:seed   (targets DATABASE_URL from .env)
import { BACKLINK_SOURCES } from "../backlink/fixtures";
import { KEYWORDS } from "../keywords/fixtures";
import { KEYWORD_THEMES } from "../keywords/types";
import { assertSeedableDb } from "./assert-test-db";
import { member, organization, user } from "./auth-schema";
import { client, db } from "./client";
import {
  backlinks,
  keywords,
  keywordThemes,
  linkSources,
  sites,
} from "./domain-schema";

const ORG_ID = "demo-org";
const OWNER_ID = "seed-owner";
const now = new Date();

const SITE_SEED = [
  {
    id: "lustre-lab",
    name: "Lustre Lab",
    url: "https://lustrelab.com",
    primaryLanguage: "en",
    languages: [] as string[],
    targetCountries: ["US"],
  },
  {
    id: "atelier-forge",
    name: "Atelier Forge",
    url: "https://atelierforge.com",
    primaryLanguage: "fr",
    languages: ["en"],
    targetCountries: ["FR", "BE"],
  },
  {
    id: "maison-aurum",
    name: "Maison Aurum",
    url: "https://maisonaurum.com",
    primaryLanguage: "fr",
    languages: [] as string[],
    targetCountries: ["FR"],
  },
];

async function seed() {
  // SEC-P4 — hard guard before any write: refuses to run against a leaked/wrong
  // DATABASE_URL (e.g. accidentally pointed at prod). Accepts seo_insight_dev
  // and seo_insight_test since this script legitimately targets both
  // (see SETUP.md) — see assertSeedableDb's doc comment for why it's not
  // assertTestDb().
  await assertSeedableDb();

  // Auth anchors (kept across runs)
  await db
    .insert(user)
    .values({
      id: OWNER_ID,
      name: "Demo Owner",
      email: "owner@seo-insight.local",
    })
    .onConflictDoNothing();
  await db
    .insert(organization)
    .values({
      id: ORG_ID,
      name: "Mon agence",
      slug: "demo",
      createdAt: now,
      // Active trial so quota-gated paths (addKeyword, MCP, createSite) work
      // against a freshly seeded dev/test DB without a Stripe subscription.
      trialEndsAt: new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000),
    })
    .onConflictDoNothing();
  await db
    .insert(member)
    .values({
      id: "seed-member",
      organizationId: ORG_ID,
      userId: OWNER_ID,
      role: "owner",
      createdAt: now,
    })
    .onConflictDoNothing();

  // Clean reseed of domain data (children first for FKs)
  await db.delete(backlinks);
  await db.delete(keywords);
  await db.delete(keywordThemes);
  await db.delete(linkSources);
  await db.delete(sites);

  await db
    .insert(sites)
    .values(
      SITE_SEED.map((s) => ({ ...s, orgId: ORG_ID, ownerUserId: OWNER_ID })),
    );

  for (const s of SITE_SEED) {
    await db.insert(keywordThemes).values(
      KEYWORD_THEMES.map((t) => ({
        id: `${s.id}-${t.id}`,
        siteId: s.id,
        slug: t.id,
        label: t.label,
      })),
    );
  }

  await db.insert(linkSources).values(
    BACKLINK_SOURCES.map((s) => ({
      id: s.id,
      orgId: ORG_ID,
      platform: s.platform,
      url: s.url,
      domainNorm: s.domainNorm,
      kind: s.kind,
      da: s.da,
      effort: s.effort,
      linkType: s.linkType,
      language: s.language,
      themes: s.themes,
      tags: s.tags,
      flags: s.flags,
      note: s.note,
    })),
  );

  await db.insert(keywords).values(
    KEYWORDS.map((k) => ({
      id: k.id,
      siteId: k.siteId,
      term: k.term,
      lang: k.locale.lang,
      country: k.locale.country,
      theme: k.theme,
      status: k.status,
      intent: k.intent,
      primarySource: k.primarySource,
      sources: k.sources,
      metrics: k.metrics,
      trend: k.trend,
      serpFeatures: k.serpFeatures,
    })),
  );

  // A few example prospects for Lustre Lab so the footprint column isn't empty.
  const sample = BACKLINK_SOURCES.slice(0, 6);
  await db.insert(backlinks).values(
    sample.map((s) => ({
      id: `lustre-lab__${s.id}`,
      linkSourceId: s.id,
      siteId: "lustre-lab",
      status: "prospect" as const,
    })),
  );

  console.log("✓ seeded:", {
    sites: SITE_SEED.length,
    keywordThemes: SITE_SEED.length * KEYWORD_THEMES.length,
    linkSources: BACKLINK_SOURCES.length,
    keywords: KEYWORDS.length,
    backlinks: sample.length,
  });
  await client.end();
}

await seed();
