// @WHO:   vps-deploy/api/kds/prisma/seed/index.ts
// @WHAT:  Seed data for KDS API — Kedai Ayam Warisan 81 demo data
// @PART:  database
// @ENTRY: main()

import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcryptjs';

const prisma = new PrismaClient();

async function main() {
  console.log('🌱 Seeding KDS API database...');

  // ── Create Outlet ──
  const outlet = await prisma.outlet.upsert({
    where: { slug: 'kedai-ayam-warisan-81' },
    update: {},
    create: {
      slug: 'kedai-ayam-warisan-81',
      name: 'Kedai Ayam Warisan 81',
      description: 'Ayam goreng resep warisan dengan bumbu rahasia yang diwariskan selama tiga generasi sejak 1981.',
      address: 'Jl. Merdeka No. 81, Kota Warisan',
      phone: '0812-3456-7890',
      image: '/kedai-ayam/outlet.jpg',
      isActive: true,
    },
  });
  console.log(`✅ Outlet: ${outlet.name}`);

  // ── Create Admin User ──
  const adminPassword = await bcrypt.hash('admin123', 10);
  const admin = await prisma.user.upsert({
    where: { email: 'admin@kaw81.com' },
    update: {},
    create: {
      email: 'admin@kaw81.com',
      name: 'Admin KAW81',
      password: adminPassword,
      phone: '0812-0000-0001',
      role: 'OUTLET_ADMIN',
    },
  });
  await prisma.userOutlet.upsert({
    where: { userId_outletId: { userId: admin.id, outletId: outlet.id } },
    update: {},
    create: {
      userId: admin.id,
      outletId: outlet.id,
      role: 'OUTLET_ADMIN',
    },
  });
  console.log(`✅ Admin: ${admin.email}`);

  // ── Create Cashier User ──
  const cashierPassword = await bcrypt.hash('cashier123', 10);
  const cashier = await prisma.user.upsert({
    where: { email: 'kasir@kaw81.com' },
    update: {},
    create: {
      email: 'kasir@kaw81.com',
      name: 'Kasir KAW81',
      password: cashierPassword,
      phone: '0812-0000-0002',
      role: 'CASHIER',
    },
  });
  await prisma.userOutlet.upsert({
    where: { userId_outletId: { userId: cashier.id, outletId: outlet.id } },
    update: {},
    create: {
      userId: cashier.id,
      outletId: outlet.id,
      role: 'CASHIER',
    },
  });
  console.log(`✅ Cashier: ${cashier.email}`);

  // ── Create Kitchen User ──
  const cookPassword = await bcrypt.hash('cook123', 10);
  const cook = await prisma.user.upsert({
    where: { email: 'dapur@kaw81.com' },
    update: {},
    create: {
      email: 'dapur@kaw81.com',
      name: 'Koki KAW81',
      password: cookPassword,
      phone: '0812-0000-0003',
      role: 'KITCHEN_COOK',
    },
  });
  await prisma.userOutlet.upsert({
    where: { userId_outletId: { userId: cook.id, outletId: outlet.id } },
    update: {},
    create: {
      userId: cook.id,
      outletId: outlet.id,
      role: 'KITCHEN_COOK',
    },
  });
  console.log(`✅ Cook: ${cook.email}`);

  // ── Create Customer User ──
  const customerPassword = await bcrypt.hash('customer123', 10);
  const customer = await prisma.user.upsert({
    where: { email: 'customer@example.com' },
    update: {},
    create: {
      email: 'customer@example.com',
      name: 'Pelanggan Demo',
      password: customerPassword,
      phone: '0812-9999-8888',
      role: 'CUSTOMER',
    },
  });
  console.log(`✅ Customer: ${customer.email}`);

  // ── Create Categories ──
  const categoriesData = [
    { name: 'Ayam Goreng', icon: '🍗', sortOrder: 0 },
    { name: 'Nasi', icon: '🍚', sortOrder: 1 },
    { name: 'Sambal & Lalapan', icon: '🌶️', sortOrder: 2 },
    { name: 'Minuman', icon: '🥤', sortOrder: 3 },
    { name: 'Paket Hemat', icon: '📦', sortOrder: 4 },
    { name: 'Camilan', icon: '🍟', sortOrder: 5 },
  ];

  const categories: Record<string, any> = {};
  for (const cat of categoriesData) {
    categories[cat.name] = await prisma.category.upsert({
      where: { outletId_name: { outletId: outlet.id, name: cat.name } },
      update: {},
      create: {
        outletId: outlet.id,
        name: cat.name,
        icon: cat.icon,
        sortOrder: cat.sortOrder,
      },
    });
  }
  console.log(`✅ Categories: ${categoriesData.length}`);

  // ── Create Menus ──
  const menusData = [
    // Ayam Goreng
    { name: 'Ayam Goreng Kremes', category: 'Ayam Goreng', price: 28000, description: 'Ayam goreng dengan kremesan renyah bumbu warisan', image: '/kedai-ayam/ayam-kremes.jpg' },
    { name: 'Ayam Goreng Sambal Matah', category: 'Ayam Goreng', price: 30000, description: 'Ayam goreng dengan sambal matah segar Bali', image: '/kedai-ayam/ayam-matah.jpg' },
    { name: 'Ayam Bakar Bumbu Kuning', category: 'Ayam Goreng', price: 32000, description: 'Ayam bakar dengan bumbu kuning rempah tradisional', image: '/kedai-ayam/ayam-bakar.jpg' },
    { name: 'Ayam Penyet Sambal Ijo', category: 'Ayam Goreng', price: 27000, description: 'Ayam penyet dengan sambal ijo Padang', image: '/kedai-ayam/ayam-penyet.jpg' },
    { name: 'Ayam Geprek Level 1-5', category: 'Ayam Goreng', price: 25000, description: 'Ayam geprek dengan pilihan level pedas', image: '/kedai-ayam/ayam-geprek.jpg' },

    // Nasi
    { name: 'Nasi Putih', category: 'Nasi', price: 5000, description: 'Nasi putih pulen', image: '/kedai-ayam/nasi-putih.jpg' },
    { name: 'Nasi Uduk', category: 'Nasi', price: 8000, description: 'Nasi uduk santan khas Betawi', image: '/kedai-ayam/nasi-uduk.jpg' },
    { name: 'Nasi Liwet', category: 'Nasi', price: 10000, description: 'Nasi liwet dengan arem-arem dan teri', image: '/kedai-ayam/nasi-liwet.jpg' },

    // Sambal & Lalapan
    { name: 'Sambal Bawang', category: 'Sambal & Lalapan', price: 5000, description: 'Sambal bawang merah renyah', image: '/kedai-ayam/sambal-bawang.jpg' },
    { name: 'Sambal Terasi', category: 'Sambal & Lalapan', price: 5000, description: 'Sambal terasi pedas nampol', image: '/kedai-ayam/sambal-terasi.jpg' },
    { name: 'Lalapan Segar', category: 'Sambal & Lalapan', price: 5000, description: 'Kol, timun, kemangi segar', image: '/kedai-ayam/lalapan.jpg' },

    // Minuman
    { name: 'Es Teh Manis', category: 'Minuman', price: 5000, description: 'Es teh manis segar', image: '/kedai-ayam/es-teh.jpg' },
    { name: 'Es Jeruk Peras', category: 'Minuman', price: 8000, description: 'Jeruk peras asli tanpa pengawet', image: '/kedai-ayam/es-jeruk.jpg' },
    { name: 'Kopi Tubruk', category: 'Minuman', price: 8000, description: 'Kopi tubruk hitam pekat', image: '/kedai-ayam/kopi-tubruk.jpg' },

    // Paket Hemat
    { name: 'Paket A: Ayam + Nasi + Es Teh', category: 'Paket Hemat', price: 35000, description: '1 pcs ayam goreng + nasi putih + es teh manis', image: '/kedai-ayam/paket-a.jpg' },
    { name: 'Paket B: 2 Ayam + 2 Nasi + 2 Es Teh', category: 'Paket Hemat', price: 65000, description: 'Paket hemat untuk 2 orang', image: '/kedai-ayam/paket-b.jpg' },
    { name: 'Paket Keluarga: 4 Ayam + 4 Nasi + Lalapan + 4 Minum', category: 'Paket Hemat', price: 120000, description: 'Paket lengkap untuk keluarga 4 orang', image: '/kedai-ayam/paket-keluarga.jpg' },

    // Camilan
    { name: 'Kentang Goreng', category: 'Camilan', price: 12000, description: 'Kentang goreng renyah dengan saus', image: '/kedai-ayam/kentang.jpg' },
    { name: 'Tahu Goreng Crispy', category: 'Camilan', price: 8000, description: 'Tahu goreng crispy isi 4', image: '/kedai-ayam/tahu-goreng.jpg' },
  ];

  const menuRecords: Record<string, any> = {};
  for (const menu of menusData) {
    const catRecord = categories[menu.category];
    if (!catRecord) continue;
    menuRecords[menu.name] = await prisma.menu.create({
      data: {
        outletId: outlet.id,
        categoryId: catRecord.id,
        name: menu.name,
        description: menu.description,
        price: menu.price,
        image: menu.image,
      },
    });
  }
  console.log(`✅ Menus: ${menusData.length}`);

  // ── Create Modifiers ──
  // Ayam Geprek - Level Pedas
  const geprek = menuRecords['Ayam Geprek Level 1-5'];
  if (geprek) {
    const levelModifier = await prisma.menuModifier.create({
      data: {
        menuId: geprek.id,
        name: 'Level Pedas',
        required: true,
        maxSelect: 1,
        options: {
          create: [
            { name: 'Level 1 - Ringan', priceAdjustment: 0, isDefault: true },
            { name: 'Level 2 - Sedang', priceAdjustment: 0 },
            { name: 'Level 3 - Pedas', priceAdjustment: 0 },
            { name: 'Level 4 - Sangat Pedas', priceAdjustment: 2000 },
            { name: 'Level 5 - Naga', priceAdjustment: 5000 },
          ],
        },
      },
    });
    console.log('✅ Modifier: Level Pedas for Ayam Geprek');
  }

  // Paket - Add-on
  const paketA = menuRecords['Paket A: Ayam + Nasi + Es Teh'];
  if (paketA) {
    const addonModifier = await prisma.menuModifier.create({
      data: {
        menuId: paketA.id,
        name: 'Tambahkan',
        required: false,
        maxSelect: 3,
        options: {
          create: [
            { name: 'Extra Sambal', priceAdjustment: 3000 },
            { name: 'Extra Nasi', priceAdjustment: 5000 },
            { name: 'Tambah Ayam', priceAdjustment: 25000 },
          ],
        },
      },
    });
    console.log('✅ Modifier: Add-on for Paket A');
  }

  // Ayam Goreng - Size
  const ayamKremes = menuRecords['Ayam Goreng Kremes'];
  if (ayamKremes) {
    const sizeModifier = await prisma.menuModifier.create({
      data: {
        menuId: ayamKremes.id,
        name: 'Ukuran',
        required: true,
        maxSelect: 1,
        options: {
          create: [
            { name: 'Reguler', priceAdjustment: 0, isDefault: true },
            { name: 'Jumbo', priceAdjustment: 8000 },
          ],
        },
      },
    });
    console.log('✅ Modifier: Size for Ayam Goreng Kremes');
  }

  // ── Create Stations ──
  const kitchen = await prisma.station.create({
    data: {
      outletId: outlet.id,
      name: 'Dapur Utama',
      type: 'KITCHEN',
    },
  });

  const cashierStation = await prisma.station.create({
    data: {
      outletId: outlet.id,
      name: 'Kasir 1',
      type: 'CASHIER',
    },
  });
  console.log('✅ Stations: 2');

  console.log('🎉 Seed complete!');
}

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