import { randomBytes } from "node:crypto";
import { PrismaClient } from "@prisma/client";
import bcrypt from "bcryptjs";
import { categories, products } from "./data/catalog";
import { productsFurnitureLeather } from "./data/catalog-furniture";
import { productsHome } from "./data/catalog-home";
import { journal } from "./data/journal";
import { settingDefaults } from "../src/lib/settings-defaults";

const prisma = new PrismaClient();
const DAY = 86_400_000;
const daysAgo = (days: number) => new Date(Date.now() - days * DAY);
const PASSWORD = process.env.SEED_PASSWORD ?? "Zellige!2025";
const ADMIN_EMAIL = process.env.SEED_ADMIN_EMAIL ?? "demo@zelij-demo.freedevlance.com";
const DEMO_ADMIN_PASSWORD = process.env.DEMO_ADMIN_PASSWORD ?? "demo1234";
const CLIENT_EMAIL = process.env.SEED_CLIENT_EMAIL ?? "client@darzellige.ma";
const SUPERADMIN_EMAIL = process.env.SEED_SUPERADMIN_EMAIL ?? "owner@darzellige.ma";
const SUPERADMIN_PASSWORD = process.env.SEED_SUPERADMIN_PASSWORD ?? randomBytes(18).toString("base64url");

const allProducts = [...products, ...productsFurnitureLeather, ...productsHome];
const locales = ["fr", "en", "ar"] as const;

type CreatedProduct = {
  id: string;
  price: number;
  name: string;
  image: string;
  stock: number;
  variants: { id: string; name: string; sku: string; priceDelta: number }[];
};

async function resetDatabase() {
  await prisma.$transaction([
    prisma.inventoryMovement.deleteMany(),
    prisma.orderItem.deleteMany(),
    prisma.order.deleteMany(),
    prisma.wishlistItem.deleteMany(),
    prisma.wishlist.deleteMany(),
    prisma.review.deleteMany(),
    prisma.cartItem.deleteMany(),
    prisma.cart.deleteMany(),
    prisma.productVariant.deleteMany(),
    prisma.productImage.deleteMany(),
    prisma.productTranslation.deleteMany(),
    prisma.product.deleteMany(),
    prisma.categoryTranslation.deleteMany(),
    prisma.category.deleteMany(),
    prisma.passwordResetToken.deleteMany(),
    prisma.customerAddress.deleteMany(),
    prisma.user.deleteMany(),
    prisma.coupon.deleteMany(),
    prisma.newsletterSubscriber.deleteMany(),
    prisma.contactMessage.deleteMany(),
    prisma.journalArticleTranslation.deleteMany(),
    prisma.journalArticle.deleteMany(),
    prisma.websiteSetting.deleteMany(),
  ]);
}

async function seedCategories() {
  const map = new Map<string, string>();
  for (const category of categories) {
    const created = await prisma.category.create({
      data: {
        slug: category.slug,
        image: category.image,
        position: category.position,
        translations: {
          create: locales.map((locale) => ({
            locale,
            name: category.texts[locale].name,
            description: category.texts[locale].description,
          })),
        },
      },
    });
    map.set(category.slug, created.id);
  }
  return map;
}

async function seedProducts(categoryMap: Map<string, string>) {
  const map = new Map<string, CreatedProduct>();

  for (const [index, product] of allProducts.entries()) {
    const category = categories.find((entry) => entry.slug === product.categorySlug);
    if (!category) throw new Error(`Unknown category ${product.categorySlug}`);
    const categoryId = categoryMap.get(product.categorySlug);
    if (!categoryId) throw new Error(`Missing category ${product.categorySlug}`);

    const reviews = product.reviews ?? [];
    const rating = reviews.length
      ? reviews.reduce((sum, review) => sum + review.rating, 0) / reviews.length
      : 4.7;

    const created = await prisma.product.create({
      data: {
        slug: product.slug,
        sku: product.sku,
        categoryId,
        price: product.price,
        compareAtPrice: product.compareAtPrice ?? null,
        costPrice: Math.round(product.price * 0.52),
        stock: product.stock,
        isFeatured: product.isFeatured ?? false,
        isPublished: true,
        rating: Number(rating.toFixed(1)),
        reviewCount: reviews.length,
        salesCount: product.salesCount,
        createdAt: daysAgo(190 - index * 5),
        translations: {
          create: locales.map((locale) => ({
            locale,
            name: product.texts[locale].name,
            shortDescription: product.texts[locale].shortDescription,
            description: product.texts[locale].description,
            materials: product.texts[locale].materials,
            dimensions: product.texts[locale].dimensions,
            origin: category.origin[locale],
            artisanName: category.artisanName,
            artisanBio: category.artisanBio[locale],
            care: category.care[locale],
          })),
        },
        images: {
          create: product.images.map((url, position) => ({
            url,
            alt: product.texts.fr.name,
            position,
          })),
        },
        variants:
          product.variants && product.variants.length > 0
            ? {
                create: product.variants.map((variant, position) => ({
                  name: variant.name,
                  sku: variant.sku,
                  priceDelta: variant.priceDelta,
                  stock: variant.stock,
                  position,
                })),
              }
            : undefined,
        reviews:
          reviews.length > 0
            ? {
                create: reviews.map((review) => ({
                  authorName: review.author,
                  rating: review.rating,
                  title: review.title,
                  comment: review.comment,
                  isSample: true,
                  createdAt: daysAgo(review.daysAgo),
                })),
              }
            : undefined,
      },
      include: { variants: true },
    });

    map.set(product.slug, {
      id: created.id,
      price: created.price,
      name: product.texts.fr.name,
      image: product.images[0],
      stock: created.stock,
      variants: created.variants.map((variant) => ({
        id: variant.id,
        name: variant.name,
        sku: variant.sku,
        priceDelta: variant.priceDelta,
      })),
    });

    await prisma.inventoryMovement.create({
      data: {
        productId: created.id,
        type: "RESTOCK",
        quantity: product.stock,
        previousStock: 0,
        newStock: product.stock,
        reason: "Stock initial — jeu de démonstration",
        createdAt: daysAgo(195),
      },
    });
  }

  return map;
}

type CustomerSeed = {
  name: string;
  email: string;
  phone: string;
  city: string;
  country: string;
  line1: string;
  postal: string;
  locale: string;
};

const customers: CustomerSeed[] = [
  {
    name: "Camille Laurent",
    email: CLIENT_EMAIL,
    phone: "+33 6 84 22 17 05",
    city: "Paris",
    country: "FR",
    line1: "24 rue de Charonne",
    postal: "75011",
    locale: "fr",
  },
  {
    name: "Yasmine Bennani",
    email: "yasmine.bennani@example.com",
    phone: "+212 6 61 44 28 90",
    city: "Casablanca",
    country: "MA",
    line1: "18, rue Ibn Batouta, Gauthier",
    postal: "20060",
    locale: "fr",
  },
  {
    name: "Marc Delaunay",
    email: "marc.delaunay@example.com",
    phone: "+33 6 12 90 44 31",
    city: "Lyon",
    country: "FR",
    line1: "7 quai Saint-Vincent",
    postal: "69001",
    locale: "fr",
  },
  {
    name: "Sofia Romero",
    email: "sofia.romero@example.com",
    phone: "+34 611 22 88 40",
    city: "Barcelona",
    country: "ES",
    line1: "Carrer de Girona, 88",
    postal: "08009",
    locale: "en",
  },
];

async function seedUsers() {
  const passwordHash = await bcrypt.hash(PASSWORD, 12);

  // Read-only demo administrator: can open the back-office but not modify it.
  const admin = await prisma.user.create({
    data: {
      name: "Compte démonstration",
      email: ADMIN_EMAIL,
      passwordHash: await bcrypt.hash(DEMO_ADMIN_PASSWORD, 12),
      phone: "+212 6 12 34 56 78",
      role: "ADMIN",
      emailVerified: daysAgo(400),
      createdAt: daysAgo(420),
    },
  });

  // Owner account: full write access.
  await prisma.user.create({
    data: {
      name: "Super Administrateur",
      email: SUPERADMIN_EMAIL,
      passwordHash: await bcrypt.hash(SUPERADMIN_PASSWORD, 12),
      role: "SUPERADMIN",
      emailVerified: daysAgo(420),
      createdAt: daysAgo(420),
    },
  });

  const created = new Map<string, { id: string; user: CustomerSeed }>();
  for (const customer of customers) {
    const user = await prisma.user.create({
      data: {
        name: customer.name,
        email: customer.email,
        passwordHash,
        phone: customer.phone,
        role: "CUSTOMER",
        emailVerified: daysAgo(120),
        createdAt: daysAgo(210),
        addresses: {
          create: {
            label: "Domicile",
            fullName: customer.name,
            phone: customer.phone,
            country: customer.country,
            city: customer.city,
            addressLine1: customer.line1,
            postalCode: customer.postal,
            isDefault: true,
          },
        },
      },
    });
    created.set(customer.email, { id: user.id, user: customer });
  }

  const camille = created.get(CLIENT_EMAIL);
  if (camille) {
    await prisma.wishlist.create({
      data: {
        userId: camille.id,
        items: {
          create: [
            { productId: (await prisma.product.findUniqueOrThrow({ where: { slug: "tapis-berbere-atlas" } })).id },
            { productId: (await prisma.product.findUniqueOrThrow({ where: { slug: "lampe-cuivre" } })).id },
          ],
        },
      },
    });
  }

  return { admin, created };
}

async function seedCoupons() {
  await prisma.coupon.createMany({
    data: [
      {
        code: "BIENVENUE10",
        type: "PERCENT",
        value: 10,
        minOrder: 0,
        maxUses: 500,
        usedCount: 0,
        isActive: true,
      },
      {
        code: "ATLAS15",
        type: "PERCENT",
        value: 15,
        minOrder: 100000,
        maxUses: 100,
        usedCount: 0,
        isActive: true,
        expiresAt: daysAgo(-120),
      },
      {
        code: "LIVRAISON",
        type: "FIXED",
        value: 4500,
        minOrder: 50000,
        usedCount: 0,
        isActive: true,
      },
      {
        code: "CASA20",
        type: "FIXED",
        value: 20000,
        minOrder: 150000,
        maxUses: 50,
        usedCount: 0,
        isActive: true,
        expiresAt: daysAgo(-60),
      },
      {
        code: "PRINTEMPS15",
        type: "PERCENT",
        value: 15,
        minOrder: 0,
        maxUses: 200,
        usedCount: 14,
        isActive: true,
        expiresAt: daysAgo(20),
      },
      {
        code: "VIP25",
        type: "PERCENT",
        value: 25,
        minOrder: 200000,
        usedCount: 0,
        isActive: false,
      },
    ],
  });
}

type OrderSeed = {
  reference: string;
  customerEmail: string;
  days: number;
  status: string;
  paymentStatus: string;
  paymentMethod: string;
  locale: string;
  items: { slug: string; quantity: number; variantName?: string }[];
  couponCode?: string;
  discountRate?: number;
};

const orders: OrderSeed[] = [
  {
    reference: "DZ-2026-100241",
    customerEmail: CLIENT_EMAIL,
    days: 0,
    status: "PENDING",
    paymentStatus: "PENDING",
    paymentMethod: "COD",
    locale: "fr",
    items: [
      { slug: "tapis-beni-ourain", quantity: 1 },
      { slug: "bols-safi", quantity: 1, variantName: "Olive" },
    ],
  },
  {
    reference: "DZ-2026-100238",
    customerEmail: "yasmine.bennani@example.com",
    days: 6,
    status: "PROCESSING",
    paymentStatus: "PAID",
    paymentMethod: "ONLINE",
    locale: "fr",
    items: [
      { slug: "lanterne-marrakech", quantity: 1, variantName: "Grande · H 50 cm" },
      { slug: "coussins-sabra", quantity: 2, variantName: "Terracotta" },
    ],
  },
  {
    reference: "DZ-2026-100229",
    customerEmail: "marc.delaunay@example.com",
    days: 14,
    status: "SHIPPED",
    paymentStatus: "PAID",
    paymentMethod: "ONLINE",
    locale: "fr",
    items: [{ slug: "table-basse-cedre", quantity: 1 }],
  },
  {
    reference: "DZ-2026-100214",
    customerEmail: "sofia.romero@example.com",
    days: 23,
    status: "DELIVERED",
    paymentStatus: "PAID",
    paymentMethod: "BANK_TRANSFER",
    locale: "en",
    items: [
      { slug: "miroir-laiton", quantity: 1 },
      { slug: "plat-tagine", quantity: 1 },
    ],
  },
  {
    reference: "DZ-2026-100198",
    customerEmail: CLIENT_EMAIL,
    days: 38,
    status: "DELIVERED",
    paymentStatus: "PAID",
    paymentMethod: "COD",
    locale: "fr",
    items: [
      { slug: "plaid-laine", quantity: 1 },
      { slug: "babouches", quantity: 1, variantName: "39" },
      { slug: "carnet-artisan", quantity: 1 },
    ],
    couponCode: "BIENVENUE10",
    discountRate: 10,
  },
  {
    reference: "DZ-2026-100176",
    customerEmail: "yasmine.bennani@example.com",
    days: 55,
    status: "DELIVERED",
    paymentStatus: "PAID",
    paymentMethod: "COD",
    locale: "fr",
    items: [{ slug: "tapis-azilal", quantity: 1 }],
  },
  {
    reference: "DZ-2026-100151",
    customerEmail: "marc.delaunay@example.com",
    days: 79,
    status: "CANCELLED",
    paymentStatus: "REFUNDED",
    paymentMethod: "ONLINE",
    locale: "fr",
    items: [{ slug: "fauteuil-rotin", quantity: 1 }],
  },
  {
    reference: "DZ-2026-100122",
    customerEmail: "sofia.romero@example.com",
    days: 104,
    status: "DELIVERED",
    paymentStatus: "PAID",
    paymentMethod: "BANK_TRANSFER",
    locale: "en",
    items: [
      { slug: "lampe-cuivre", quantity: 1 },
      { slug: "encensoir", quantity: 2 },
    ],
  },
  {
    reference: "DZ-2026-10096",
    customerEmail: CLIENT_EMAIL,
    days: 133,
    status: "DELIVERED",
    paymentStatus: "PAID",
    paymentMethod: "COD",
    locale: "fr",
    items: [{ slug: "coffret-ceramique", quantity: 1 }],
  },
  {
    reference: "DZ-2026-10061",
    customerEmail: "yasmine.bennani@example.com",
    days: 168,
    status: "DELIVERED",
    paymentStatus: "PAID",
    paymentMethod: "ONLINE",
    locale: "fr",
    items: [{ slug: "banquette-cuir", quantity: 1 }],
  },
  {
    reference: "DZ-2026-10024",
    customerEmail: "marc.delaunay@example.com",
    days: 190,
    status: "DELIVERED",
    paymentStatus: "PAID",
    paymentMethod: "COD",
    locale: "fr",
    items: [
      { slug: "plateau-noyer", quantity: 1 },
      { slug: "service-the", quantity: 1, variantName: "6 verres" },
    ],
  },
];

function shippingFor(country: string, subtotal: number) {
  if (country === "MA") return subtotal >= 150000 ? 0 : 4500;
  if (["FR", "ES", "IT", "DE", "BE", "NL", "PT", "LU", "IE", "AT"].includes(country)) return 25000;
  return 40000;
}

async function seedOrders(
  customersMap: Map<string, { id: string; user: CustomerSeed }>,
  productMap: Map<string, CreatedProduct>,
) {
  for (const order of orders) {
    const customer = customersMap.get(order.customerEmail);
    if (!customer) throw new Error(`Unknown customer ${order.customerEmail}`);

    const lines = order.items.map((item) => {
      const product = productMap.get(item.slug);
      if (!product) throw new Error(`Unknown product ${item.slug}`);
      const variant = item.variantName
        ? product.variants.find((entry) => entry.name === item.variantName)
        : undefined;
      if (item.variantName && !variant) {
        throw new Error(`Unknown variant ${item.variantName} for ${item.slug}`);
      }
      const unitPrice = product.price + (variant?.priceDelta ?? 0);
      return {
        productId: product.id,
        variantId: variant?.id ?? null,
        name: product.name,
        variantName: variant?.name ?? null,
        sku: variant?.sku ?? `${item.slug.toUpperCase()}`,
        image: product.image,
        unitPrice,
        quantity: item.quantity,
        total: unitPrice * item.quantity,
      };
    });

    const subtotal = lines.reduce((sum, line) => sum + line.total, 0);
    const discount = order.couponCode
      ? Math.round((subtotal * (order.discountRate ?? 0)) / 100)
      : 0;
    const shipping = shippingFor(customer.user.country, subtotal - discount);
    const total = subtotal - discount + shipping;
    const createdAt = daysAgo(order.days);

    await prisma.order.create({
      data: {
        reference: order.reference,
        userId: customer.id,
        status: order.status,
        paymentStatus: order.paymentStatus,
        paymentMethod: order.paymentMethod,
        customerName: customer.user.name,
        email: customer.user.email,
        phone: customer.user.phone,
        country: customer.user.country,
        city: customer.user.city,
        addressLine1: customer.user.line1,
        postalCode: customer.user.postal,
        subtotal,
        discount,
        shipping,
        total,
        locale: order.locale,
        couponCode: order.couponCode ?? null,
        createdAt,
        updatedAt: daysAgo(Math.max(0, order.days - 1)),
        items: { create: lines },
      },
    });

    if (order.couponCode) {
      await prisma.coupon.update({
        where: { code: order.couponCode },
        data: { usedCount: { increment: 1 } },
      });
    }
  }
}

async function seedContent() {
  for (const article of journal) {
    await prisma.journalArticle.create({
      data: {
        slug: article.slug,
        image: article.image,
        author: article.author,
        isPublished: true,
        publishedAt: daysAgo(article.daysAgo),
        translations: {
          create: locales.map((locale) => ({
            locale,
            title: article.texts[locale].title,
            excerpt: article.texts[locale].excerpt,
            content: article.texts[locale].content,
          })),
        },
      },
    });
  }

  await prisma.newsletterSubscriber.createMany({
    data: [
      { email: "lea.martin@example.com", locale: "fr", createdAt: daysAgo(18) },
      { email: "james.whitmore@example.com", locale: "en", createdAt: daysAgo(44) },
      { email: "salma.idrissi@example.com", locale: "ar", createdAt: daysAgo(77) },
      { email: "pablo.garcia@example.com", locale: "en", createdAt: daysAgo(112) },
    ],
  });

  await prisma.contactMessage.createMany({
    data: [
      {
        name: "Claire Dubois",
        email: "claire.dubois@example.com",
        subject: "Grand tapis sur mesure",
        message:
          "Bonjour, je souhaiterais savoir s'il est possible de commander un tapis Beni Ouarain en 300 × 400 cm. Merci pour votre retour.",
        isRead: false,
        createdAt: daysAgo(3),
      },
      {
        name: "Hicham Alaoui",
        email: "hicham.alaoui@example.com",
        subject: "Livraison à Casablanca",
        message:
          "Bonjour, j'ai commandé une lanterne la semaine dernière. Pouvez-vous me confirmer le délai de livraison ? Merci.",
        isRead: true,
        createdAt: daysAgo(9),
      },
      {
        name: "Elena Rossi",
        email: "elena.rossi@example.com",
        subject: "Collaboration intérieurs",
        message:
          "Bonjour, je suis architecte d'intérieur à Milan et je travaille sur un projet d'hôtel. Je souhaite recevoir votre catalogue professionnel.",
        isRead: false,
        createdAt: daysAgo(15),
      },
    ],
  });
}

async function seedSettings() {
  const groups: Record<string, string> = {
    brand: "general",
    site: "general",
    announcement: "content",
    hero: "content",
    story: "content",
    collection: "content",
    craft: "content",
    footer: "contact",
    contact: "contact",
    social: "social",
    seo: "seo",
    shipping: "shipping",
  };

  for (const [key, value] of Object.entries(settingDefaults)) {
    const prefix = key.split(".")[0] ?? "general";
    await prisma.websiteSetting.create({
      data: { key, value, group: groups[prefix] ?? "general" },
    });
  }
}

async function main() {
  console.log("Resetting database…");
  await resetDatabase();

  console.log("Seeding categories…");
  const categoryMap = await seedCategories();

  console.log("Seeding products, images and reviews…");
  const productMap = await seedProducts(categoryMap);

  console.log("Seeding users…");
  const { created } = await seedUsers();

  console.log("Seeding coupons…");
  await seedCoupons();

  console.log("Seeding sample orders…");
  await seedOrders(created, productMap);

  console.log("Seeding journal, newsletter and messages…");
  await seedContent();

  console.log("Seeding website settings…");
  await seedSettings();

  const [productCount, orderCount, userCount] = await Promise.all([
    prisma.product.count(),
    prisma.order.count(),
    prisma.user.count(),
  ]);

  console.log("");
  console.log("DAR ZELLIGE — demo database ready");
  console.log(`  ${categoryMap.size} categories · ${productCount} products · ${orderCount} orders · ${userCount} users`);
  console.log(`  Admin (demo, read-only): ${ADMIN_EMAIL} / ${DEMO_ADMIN_PASSWORD}`);
  console.log(`  Superadmin (full access): ${SUPERADMIN_EMAIL} / ${SUPERADMIN_PASSWORD}`);
  console.log(`  Client: ${CLIENT_EMAIL} / ${PASSWORD}`);
  console.log("");
}

main()
  .catch((error) => {
    console.error("Seed failed:", error);
    process.exitCode = 1;
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
