import { config } from "dotenv";
import path from "node:path";
config({ path: path.resolve(process.cwd(), ".env.local") });
config({ path: path.resolve(process.cwd(), ".env") });

type CategoryDef = {
  slug: string;
  name: string;
  description: string;
};

const CATEGORIES: CategoryDef[] = [
  {
    slug: "books",
    name: "Books",
    description: "Essential orthopaedic references and exam revision texts.",
  },
  {
    slug: "merch",
    name: "OrthoGlobe merch",
    description: "Collaborative-branded merch for members.",
  },
];

type ProductDef = {
  slug: string;
  title: string;
  shortDescription: string;
  description: string;
  categorySlug: string;
  priceMinor: number;
  currency: string;
  sku: string;
  stockStatus: "in_stock" | "out_of_stock" | "preorder" | "coming_soon";
  coverImage: string | null;
  memberOnly: boolean;
};

const PRODUCTS: ProductDef[] = [
  {
    slug: "frcs-core-review",
    title: "FRCS Core Review — OrthoGlobe Edition",
    shortDescription:
      "A 600-page revision text covering every syllabus topic, with 1,300 OrthoPrep MCQs cross-referenced by chapter.",
    description:
      "## What's inside\n\n- Full coverage of the FRCS (Tr & Orth) syllabus, updated for the 2026 curriculum\n- 1,300 cross-referenced MCQs with fully worked explanations\n- Foldable anatomy plates and high-yield summary tables\n\nHardback, 2.1 kg. Ships worldwide with tracked delivery.",
    categorySlug: "books",
    priceMinor: 49_00,
    currency: "GBP",
    sku: "OG-BOOK-FRCS-01",
    stockStatus: "in_stock",
    coverImage: null,
    memberOnly: false,
  },
  {
    slug: "orthoglobe-lab-coat",
    title: "OrthoGlobe Lab Coat (Unisex)",
    shortDescription:
      "Heavy-weight cotton lab coat with the OrthoGlobe wordmark embroidered on the left chest.",
    description:
      "Workhorse lab coat for ward rounds and clinic. 100% cotton, 260 gsm. Machine-washable at 60°C. Sizes XS–XXL.",
    categorySlug: "merch",
    priceMinor: 38_00,
    currency: "GBP",
    sku: "OG-MERCH-COAT-01",
    stockStatus: "in_stock",
    coverImage: null,
    memberOnly: true,
  },
  {
    slug: "orthoglobe-enamel-pin",
    title: "OrthoGlobe Enamel Pin",
    shortDescription:
      "Hard-enamel pin of the OrthoGlobe mark. Collector item handed out at global meets.",
    description:
      "Hard enamel on a nickel base, 22 mm wide. Packaged with a backing card signed by the steering committee.",
    categorySlug: "merch",
    priceMinor: 8_00,
    currency: "GBP",
    sku: "OG-MERCH-PIN-01",
    stockStatus: "in_stock",
    coverImage: null,
    memberOnly: false,
  },
];

async function main() {
  if (!process.env.DATABASE_URL) throw new Error("DATABASE_URL not set");

  const postgres = (await import("postgres")).default;
  const { drizzle } = await import("drizzle-orm/postgres-js");
  const { eq } = await import("drizzle-orm");
  const schema = await import("../src/lib/db/schema");

  const sql = postgres(process.env.DATABASE_URL!, { max: 1 });
  const db = drizzle(sql, { schema });

  let catInserted = 0;
  const catBySlug = new Map<string, string>();
  for (const c of CATEGORIES) {
    const [existing] = await db
      .select({ id: schema.storeCategories.id })
      .from(schema.storeCategories)
      .where(eq(schema.storeCategories.slug, c.slug))
      .limit(1);
    if (existing) {
      catBySlug.set(c.slug, existing.id);
      continue;
    }
    const [row] = await db
      .insert(schema.storeCategories)
      .values(c)
      .returning({ id: schema.storeCategories.id });
    catBySlug.set(c.slug, row.id);
    catInserted += 1;
  }

  let prodInserted = 0;
  for (const p of PRODUCTS) {
    const [existing] = await db
      .select({ id: schema.storeProducts.id })
      .from(schema.storeProducts)
      .where(eq(schema.storeProducts.slug, p.slug))
      .limit(1);
    if (existing) continue;
    await db.insert(schema.storeProducts).values({
      slug: p.slug,
      title: p.title,
      shortDescription: p.shortDescription,
      description: p.description,
      categoryId: catBySlug.get(p.categorySlug) ?? null,
      priceMinor: p.priceMinor,
      currency: p.currency,
      sku: p.sku,
      stockStatus: p.stockStatus,
      coverImage: p.coverImage,
      memberOnly: p.memberOnly,
      status: "published",
      publishedAt: new Date(),
    });
    prodInserted += 1;
  }

  console.log(
    `Seeded ${catInserted}/${CATEGORIES.length} categories and ${prodInserted}/${PRODUCTS.length} products.`,
  );
  await sql.end();
}

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