import "dotenv/config";
import { PrismaBetterSqlite3 } from "@prisma/adapter-better-sqlite3";
import { PrismaClient } from "../src/generated/prisma/client";
import { hashPassword } from "../src/lib/password";
import { DEFAULT_PUBLIC_SITE_COPY } from "../src/lib/site-content-defaults";
import { WAFFLE_CATEGORIES } from "../src/lib/constants";
import { formatDateIso } from "../src/lib/week-calendar";

const url = process.env.DATABASE_URL ?? "file:./dev.db";
const adapter = new PrismaBetterSqlite3({ url });
const prisma = new PrismaClient({ adapter });

async function main() {
  const email =
    process.env.ADMIN_EMAIL?.trim().toLowerCase() || "admin@lagaufredor.local";
  const password = process.env.ADMIN_PASSWORD || "changeme123";

  const existing = await prisma.user.findUnique({ where: { email } });
  if (!existing) {
    await prisma.user.create({
      data: {
        email,
        passwordHash: await hashPassword(password),
      },
    });
    console.log(
      `Compte admin créé : ${email} (mot de passe : variable ADMIN_PASSWORD ou défaut changeme123)`
    );
  }

  const count = await prisma.waffle.count();
  if (count === 0) {
    await prisma.waffle.createMany({
      data: [
        {
          name: "Coco-Belge",
          ingredients:
            "Pâte Liège, perles de sucre, noix de coco râpée, touche de vanille Bourbon.",
          price: 6.5,
          isNew: true,
          category: WAFFLE_CATEGORIES.DU_MOIS,
          imageUrl: "/gallery/hero-coco.png",
        },
        {
          name: "Classique dorée",
          ingredients: "Sucre perlé, beurre AOP, sirop d’érable ou chocolat.",
          price: 5.9,
          isNew: false,
          category: WAFFLE_CATEGORIES.SUCREE,
          imageUrl: "/gallery/gaufres-sucrees.png",
        },
        {
          name: "Bubble chantilly",
          ingredients: "Bubble waffle, chantilly maison, copeaux de chocolat noir.",
          price: 7.2,
          isNew: false,
          category: WAFFLE_CATEGORIES.SUCREE,
          imageUrl: "/gallery/bubble-waffle.png",
        },
        {
          name: "Montagnarde",
          ingredients:
            "Pâte aux herbes, comté fondant, jambon cru, poivre noir concassé.",
          price: 8.5,
          isNew: false,
          category: WAFFLE_CATEGORIES.SALEE,
          imageUrl: "/gallery/gaufre-salee.png",
        },
        {
          name: "Bacon & ciboulette",
          ingredients: "Crème légère, bacon croustillant, ciboulette fraîche.",
          price: 7.9,
          isNew: false,
          category: WAFFLE_CATEGORIES.SALEE,
          imageUrl: "/gallery/gaufre-salee.png",
        },
      ],
    });
    console.log("Gaufres d’exemple insérées.");
  }

  const galleryCount = await prisma.galleryImage.count();
  if (galleryCount === 0) {
    await prisma.galleryImage.createMany({
      data: [
        {
          imageUrl: "/gallery/hero-coco.png",
          alt: "Gaufres belges caramélisées sur ardoise, noix de coco et drapeau belge.",
          sortOrder: 0,
        },
        {
          imageUrl: "/gallery/gaufres-sucrees.png",
          alt: "Stack de gaufres dorées, sucre glace et sirop.",
          sortOrder: 1,
        },
        {
          imageUrl: "/gallery/bubble-waffle.png",
          alt: "Bubble waffles en cornet, chantilly et chocolat.",
          sortOrder: 2,
        },
        {
          imageUrl: "/gallery/gaufre-salee.png",
          alt: "Gaufre salée aux herbes, crème, bacon et ciboulette.",
          sortOrder: 3,
        },
      ],
    });
    console.log("Galerie d’exemple insérée.");
  }

  await prisma.siteContent.upsert({
    where: { id: "default" },
    create: {
      id: "default",
      ...DEFAULT_PUBLIC_SITE_COPY,
    },
    update: {},
  });

  const truckCount = await prisma.truckEvent.count();
  if (truckCount === 0) {
    const start = new Date();
    const day = start.getDay();
    const diff = day === 0 ? -6 : 1 - day;
    start.setDate(start.getDate() + diff);

    const dateAt = (offset: number) => {
      const d = new Date(start);
      d.setDate(start.getDate() + offset);
      return formatDateIso(d);
    };

    await prisma.truckEvent.createMany({
      data: [
        {
          eventDate: dateAt(1),
          timeLabel: "9h — 13h",
          location: "Marché de Bagnols-sur-Cèze",
          note: "Place du marché",
        },
        {
          eventDate: dateAt(3),
          timeLabel: "11h — 19h",
          location: "Festival gourmand — Uzès",
          note: "",
        },
        {
          eventDate: dateAt(5),
          timeLabel: "10h — 18h",
          location: "Place de la République, Alès",
          note: "Food truck zone nord",
        },
      ],
    });
    console.log("Événements food truck d’exemple insérés.");
  }

  const recurCount = await prisma.truckEventRecurrence.count();
  if (recurCount === 0) {
    await prisma.truckEventRecurrence.create({
      data: {
        dayOfWeek: 1,
        timeLabel: "9h — 13h",
        location: "Marché hebdomadaire — Bagnols-sur-Cèze",
        note: "Place du marché",
      },
    });
    console.log("Récurrence food truck d’exemple insérée.");
  }
}

main()
  .then(() => prisma.$disconnect())
  .catch((e) => {
    console.error(e);
    prisma.$disconnect();
    process.exit(1);
  });
