import { PrismaClient } from "../src/generated/prisma/client";
import { scrypt, randomBytes } from "crypto";
import { promisify } from "util";
import * as dotenv from "dotenv";

// Load environment variables
dotenv.config();

const scryptAsync = promisify(scrypt);
const prisma = new PrismaClient();

async function main() {
  console.log("🌱 Starting seed...");

  // Create guide users
  const guide1 = await prisma.user.upsert({
    where: { email: "maria@zurichguide.com" },
    update: {},
    create: {
      id: "guide-maria-001",
      email: "maria@zurichguide.com",
      name: "Maria Schmidt",
      role: "GUIDE",
      bio: "Born and raised in Zurich, I've been sharing my love for this beautiful city for over 10 years. With a background in art history and a passion for storytelling, I create unforgettable experiences that blend culture, history, and local insights. Let me show you the Zurich that guidebooks miss!",
      image: "https://api.dicebear.com/7.x/avataaars/svg?seed=Maria",
      university: "University of Zurich (UZH)",
      semester: "Graduated",
      countryOfOrigin: "CH",
    },
  });

  const guide2 = await prisma.user.upsert({
    where: { email: "hans@zurichguide.com" },
    update: {},
    create: {
      id: "guide-hans-002",
      email: "hans@zurichguide.com",
      name: "Hans Mueller",
      role: "GUIDE",
      bio: "Nature enthusiast and certified mountain guide with 15 years of experience. I specialize in outdoor adventures and scenic tours around Zurich. Whether it's hiking the Alps or cruising Lake Zurich, I'll help you discover Switzerland's natural beauty.",
      image: "https://api.dicebear.com/7.x/avataaars/svg?seed=Hans",
      university: "ETH Zurich (Swiss Federal Institute of Technology)",
      semester: "Alumni",
      countryOfOrigin: "CH",
    },
  });

  const guide3 = await prisma.user.upsert({
    where: { email: "lisa@zurichguide.com" },
    update: {},
    create: {
      id: "guide-lisa-003",
      email: "lisa@zurichguide.com",
      name: "Lisa Weber",
      role: "GUIDE",
      bio: "Food and wine expert with a culinary degree from Le Cordon Bleu. I've spent the last 8 years exploring Zurich's gastronomic scene and creating unique food experiences. Join me for a delicious journey through Swiss cuisine!",
      image: "https://api.dicebear.com/7.x/avataaars/svg?seed=Lisa",
      university: "Zurich University of Applied Sciences (ZHAW)",
      semester: "Graduated",
      countryOfOrigin: "CH",
    },
  });

  const guide4 = await prisma.user.upsert({
    where: { email: "thomas@zurichguide.com" },
    update: {},
    create: {
      id: "guide-thomas-004",
      email: "thomas@zurichguide.com",
      name: "Thomas Richter",
      role: "GUIDE",
      bio: "Professional photographer and urban explorer. I love capturing Zurich's hidden corners and teaching others to see the city through a photographer's lens. My tours combine sightseeing with photography tips for stunning vacation photos.",
      image: "https://api.dicebear.com/7.x/avataaars/svg?seed=Thomas",
      university: "Zurich University of the Arts (ZHdK)",
      semester: "Fall 2025",
      countryOfOrigin: "DE",
    },
  });

  const guide5 = await prisma.user.upsert({
    where: { email: "sophie@zurichguide.com" },
    update: {},
    create: {
      id: "guide-sophie-005",
      email: "sophie@zurichguide.com",
      name: "Sophie Keller",
      role: "GUIDE",
      bio: "Family-friendly tour specialist with a background in education. I create engaging experiences for all ages, making history and culture accessible and fun for children and adults alike. Perfect for family vacations!",
      image: "https://api.dicebear.com/7.x/avataaars/svg?seed=Sophie",
      university: "University of Teacher Education Zurich (PH Zürich)",
      semester: "Spring 2025",
      countryOfOrigin: "AT",
    },
  });

  console.log("✅ Created guide users");

  // Create explorer users
  const explorer1 = await prisma.user.upsert({
    where: { email: "john@example.com" },
    update: {},
    create: {
      id: "explorer-john-001",
      email: "john@example.com",
      name: "John Anderson",
      role: "EXPLORER",
      bio: "Travel enthusiast from California. Love exploring European cities and their rich history!",
      image: "https://api.dicebear.com/7.x/avataaars/svg?seed=John",
      university: "University of Zurich (UZH)",
      semester: "Fall 2025",
      countryOfOrigin: "US",
    },
  });

  const explorer2 = await prisma.user.upsert({
    where: { email: "sarah@example.com" },
    update: {},
    create: {
      id: "explorer-sarah-002",
      email: "sarah@example.com",
      name: "Sarah Martinez",
      role: "EXPLORER",
      bio: "Foodie and wine lover exploring the world one city at a time.",
      image: "https://api.dicebear.com/7.x/avataaars/svg?seed=Sarah",
      university: "ETH Zurich (Swiss Federal Institute of Technology)",
      semester: "Spring 2025",
      countryOfOrigin: "ES",
    },
  });

  const explorer3 = await prisma.user.upsert({
    where: { email: "david@example.com" },
    update: {},
    create: {
      id: "explorer-david-003",
      email: "david@example.com",
      name: "David Chen",
      role: "EXPLORER",
      bio: "Photography hobbyist and adventure seeker from Singapore.",
      image: "https://api.dicebear.com/7.x/avataaars/svg?seed=David",
      university: "Zurich University of Applied Sciences (ZHAW)",
      semester: "Fall 2025",
      countryOfOrigin: "SG",
    },
  });

  const explorer4 = await prisma.user.upsert({
    where: { email: "emma@example.com" },
    update: {},
    create: {
      id: "explorer-emma-004",
      email: "emma@example.com",
      name: "Emma Johnson",
      role: "EXPLORER",
      bio: "Art and culture enthusiast from London. Always looking for unique experiences.",
      image: "https://api.dicebear.com/7.x/avataaars/svg?seed=Emma",
      university: "University of Zurich (UZH)",
      semester: "Exchange Student",
      countryOfOrigin: "GB",
    },
  });

  const explorer5 = await prisma.user.upsert({
    where: { email: "michael@example.com" },
    update: {},
    create: {
      id: "explorer-michael-005",
      email: "michael@example.com",
      name: "Michael Brown",
      role: "EXPLORER",
      bio: "Nature lover and hiking enthusiast from Australia.",
      image: "https://api.dicebear.com/7.x/avataaars/svg?seed=Michael",
      university: "ETH Zurich (Swiss Federal Institute of Technology)",
      semester: "Fall 2025",
      countryOfOrigin: "AU",
    },
  });

  console.log("✅ Created explorer users");

  // Create comprehensive tours
  const tours = [
    {
      slug: "old-town-walking-tour",
      title: "Historic Old Town Walking Tour",
      description:
        "Discover the charming cobblestone streets of Zurich's historic Old Town (Altstadt). This walking tour takes you through centuries of history, from medieval guildhalls to baroque churches. You'll learn about the city's fascinating past while enjoying stunning architecture and hidden courtyards that most visitors miss. Visit Grossmünster, Fraumünster with its Chagall windows, and the picturesque Lindenhof hill with panoramic views. Perfect for history buffs and culture enthusiasts!",
      city: "Zurich",
      meetingPoint: "Grossmünster Church, Grossmünsterplatz",
      meetingPointLat: 47.3702,
      meetingPointLng: 8.5439,
      durationMin: 180,
      priceCents: 4500,
      maxGuests: 12,
      tags: ["History", "Walking", "Old Town", "Architecture", "Culture"],
      included: [
        "Professional local guide",
        "Walking tour of Old Town",
        "Historical anecdotes and stories",
        "Photo opportunities at key landmarks",
        "Visit to Grossmünster and Fraumünster",
      ],
      createdById: guide1.id,
      published: true,
      avgRating: 4.9,
      reviewCount: 28,
    },
    {
      slug: "zurich-food-wine-experience",
      title: "Zurich Food & Wine Experience",
      description:
        "Embark on a culinary journey through Zurich's finest food establishments. Taste authentic Swiss cuisine including fondue, raclette, and rösti. Sample local wines from the Zurich wine region and artisanal chocolates. This tour combines food, culture, and history for an unforgettable gastronomic experience. Visit traditional restaurants, hidden cafes, and a local market. Learn about Swiss food traditions and get insider tips on the best places to eat in Zurich.",
      city: "Zurich",
      meetingPoint: "Paradeplatz",
      meetingPointLat: 47.3695,
      meetingPointLng: 8.5391,
      durationMin: 240,
      priceCents: 8900,
      maxGuests: 8,
      tags: ["Food", "Wine", "Culinary", "Culture", "Gastronomy"],
      included: [
        "Food tastings at 5 venues",
        "Wine pairings (3 varieties)",
        "Expert food guide",
        "All food and drinks included",
        "Recipe cards to take home",
      ],
      createdById: guide3.id,
      published: true,
      avgRating: 5.0,
      reviewCount: 42,
    },
    {
      slug: "lake-zurich-mountain-views",
      title: "Lake Zurich & Alpine Mountain Views",
      description:
        "Experience the natural beauty of Zurich with this scenic tour combining lake cruising and mountain vistas. Travel by boat across the pristine Lake Zurich, enjoying views of the Alps and lakeside villages. Then ascend to Uetliberg mountain by train for breathtaking 360-degree panoramas. On clear days, see over 40 mountain peaks! Perfect for nature lovers and photography enthusiasts. Includes time for refreshments at the mountain top restaurant (food not included).",
      city: "Zurich",
      meetingPoint: "Bürkliplatz Boat Terminal",
      meetingPointLat: 47.3664,
      meetingPointLng: 8.5391,
      durationMin: 300,
      priceCents: 6500,
      maxGuests: 15,
      tags: ["Nature", "Lake", "Mountains", "Scenic", "Photography"],
      included: [
        "Lake boat cruise (1 hour)",
        "Mountain railway tickets",
        "Professional nature guide",
        "Photo stops at scenic viewpoints",
        "Binoculars provided",
      ],
      createdById: guide2.id,
      published: true,
      avgRating: 4.8,
      reviewCount: 35,
    },
    {
      slug: "art-museum-tour",
      title: "Zurich Art & Museum Tour",
      description:
        "Immerse yourself in Zurich's rich artistic heritage. Visit world-class museums featuring works from medieval times to contemporary art. Explore the Kunsthaus with its impressive collection of Swiss and international art, including works by Giacometti, Monet, and Picasso. Your knowledgeable art historian guide will provide insights into artistic movements and help you appreciate masterpieces. Optional visit to the Rietberg Museum for non-European art. Small group for an intimate experience.",
      city: "Zurich",
      meetingPoint: "Kunsthaus Zurich Main Entrance",
      meetingPointLat: 47.3700,
      meetingPointLng: 8.5487,
      durationMin: 210,
      priceCents: 5500,
      maxGuests: 10,
      tags: ["Art", "Museums", "Culture", "Indoor", "History"],
      included: [
        "Museum entrance fees",
        "Art history expert guide",
        "Visit to 2-3 major museums",
        "Skip-the-line access",
        "Art appreciation guide booklet",
      ],
      createdById: guide1.id,
      published: true,
      avgRating: 4.7,
      reviewCount: 19,
    },
    {
      slug: "swiss-chocolate-workshop",
      title: "Swiss Chocolate Workshop",
      description:
        "Learn the art of Swiss chocolate making in this hands-on workshop. Create your own chocolate creations while discovering the secrets behind Switzerland's famous confectionery tradition. Take home your handmade chocolates and newfound skills to impress friends and family.",
      city: "Zurich",
      durationMin: 150,
      priceCents: 7500,
      maxGuests: 6,
      tags: ["Workshop", "Chocolate", "Hands-on", "Family-Friendly"],
      included: [
        "All materials and ingredients",
        "Expert chocolatier instruction",
        "Create your own chocolates",
        "Take home your creations",
      ],
      createdById: guide3.id,
      published: true,
      avgRating: 4.9,
      reviewCount: 51,
    },
    {
      slug: "zurich-by-night",
      title: "Zurich by Night",
      description:
        "See Zurich transform as the sun sets on this enchanting evening tour. Experience the city's vibrant nightlife, illuminated landmarks, and atmospheric streets. End the tour at a traditional Swiss restaurant for dinner (optional, not included).",
      city: "Zurich",
      durationMin: 180,
      priceCents: 5000,
      maxGuests: 12,
      tags: ["Evening", "Photography", "Nightlife", "Atmospheric"],
      included: [
        "Evening walking tour",
        "Photo opportunities at lit landmarks",
        "Local insights and recommendations",
        "Visit to scenic viewpoints",
      ],
      createdById: guide3.id,
      published: true,
      avgRating: 4.6,
      reviewCount: 23,
    },
  ];

  const createdTours: any[] = [];
  for (const tour of tours) {
    const createdTour = await prisma.tour.upsert({
      where: { slug: tour.slug },
      update: {},
      create: tour,
    });
    createdTours.push(createdTour);
  }

  console.log("✅ Created comprehensive tours");

  // Create tour images (only for the 6 tours we created)
  const tourImages = [
    // Old Town Walking Tour (index 0)
    { tourId: createdTours[0].id, url: "https://images.unsplash.com/photo-1516550893923-42d28e5677af?w=800", altText: "Zurich Old Town Aerial View", order: 0 },
    { tourId: createdTours[0].id, url: "https://images.unsplash.com/photo-1527004013197-933c4bb611b3?w=800", altText: "Grossmünster Church", order: 1 },
    { tourId: createdTours[0].id, url: "https://images.unsplash.com/photo-1565008576549-57569a49371d?w=800", altText: "Cobblestone Streets", order: 2 },
    
    // Food & Wine Tour (index 1)
    { tourId: createdTours[1].id, url: "https://images.unsplash.com/photo-1559056199-641a0ac8b55e?w=800", altText: "Swiss Cheese Platter", order: 0 },
    { tourId: createdTours[1].id, url: "https://images.unsplash.com/photo-1510812431401-41d2bd2722f3?w=800", altText: "Wine Tasting", order: 1 },
    { tourId: createdTours[1].id, url: "https://images.unsplash.com/photo-1414235077428-338989a2e8c0?w=800", altText: "Swiss Cuisine", order: 2 },
    
    // Lake & Mountain Tour (index 2)
    { tourId: createdTours[2].id, url: "https://images.unsplash.com/photo-1531366936337-7c912a4589a7?w=800", altText: "Lake Zurich View", order: 0 },
    { tourId: createdTours[2].id, url: "https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800", altText: "Mountain Vista", order: 1 },
    { tourId: createdTours[2].id, url: "https://images.unsplash.com/photo-1464207687429-7505649dae38?w=800", altText: "Alpine Panorama", order: 2 },
    
    // Art Museum Tour (index 3)
    { tourId: createdTours[3].id, url: "https://images.unsplash.com/photo-1577083165633-14ebcdb0f658?w=800", altText: "Kunsthaus Interior", order: 0 },
    { tourId: createdTours[3].id, url: "https://images.unsplash.com/photo-1564399579883-451a5d44ec08?w=800", altText: "Art Gallery", order: 1 },
    
    // Chocolate Workshop (index 4)
    { tourId: createdTours[4].id, url: "https://images.unsplash.com/photo-1511381939415-e44015466834?w=800", altText: "Swiss Chocolate", order: 0 },
    { tourId: createdTours[4].id, url: "https://images.unsplash.com/photo-1548848975-e2706d49c1b3?w=800", altText: "Chocolate Making", order: 1 },
    { tourId: createdTours[4].id, url: "https://images.unsplash.com/photo-1605870445919-838d190e8e1b?w=800", altText: "Chocolate Truffles", order: 2 },
    
    // Night Photography Tour (index 5)
    { tourId: createdTours[5].id, url: "https://images.unsplash.com/photo-1551881192-699b6ef4f6b7?w=800", altText: "Zurich at Night", order: 0 },
    { tourId: createdTours[5].id, url: "https://images.unsplash.com/photo-1467269204594-9661b134dd2b?w=800", altText: "City Lights", order: 1 },
  ];

  for (const image of tourImages) {
    await prisma.tourImage.create({ data: image });
  }

  console.log("✅ Created tour images");

  // Create bookings
  const bookings = [
    // Completed bookings
    {
      tourId: createdTours[0].id,
      userId: explorer1.id,
      date: new Date("2025-10-15"),
      numberOfGuests: 2,
      totalPrice: 9000,
      status: "COMPLETED" as const,
      notes: "Excited to explore the Old Town!",
    },
    {
      tourId: createdTours[1].id,
      userId: explorer2.id,
      date: new Date("2025-10-20"),
      numberOfGuests: 2,
      totalPrice: 17800,
      status: "COMPLETED" as const,
      notes: "Can't wait to taste Swiss cuisine!",
    },
    {
      tourId: createdTours[2].id,
      userId: explorer3.id,
      date: new Date("2025-10-22"),
      numberOfGuests: 1,
      totalPrice: 6500,
      status: "COMPLETED" as const,
    },
    {
      tourId: createdTours[4].id,
      userId: explorer4.id,
      date: new Date("2025-10-25"),
      numberOfGuests: 3,
      totalPrice: 22500,
      status: "COMPLETED" as const,
      notes: "Making chocolates with my kids!",
    },
    
    // Confirmed upcoming bookings
    {
      tourId: createdTours[0].id,
      userId: explorer5.id,
      date: new Date("2025-11-05"),
      numberOfGuests: 2,
      totalPrice: 9000,
      status: "CONFIRMED" as const,
    },
    {
      tourId: createdTours[5].id,
      userId: explorer1.id,
      date: new Date("2025-11-08"),
      numberOfGuests: 1,
      totalPrice: 5000,
      status: "CONFIRMED" as const,
      notes: "Bringing my camera!",
    },
    {
      tourId: createdTours[1].id,
      userId: explorer2.id,
      date: new Date("2025-11-10"),
      numberOfGuests: 2,
      totalPrice: 17800,
      status: "CONFIRMED" as const,
    },
    {
      tourId: createdTours[2].id,
      userId: explorer3.id,
      date: new Date("2025-11-12"),
      numberOfGuests: 4,
      totalPrice: 26000,
      status: "CONFIRMED" as const,
      notes: "Family trip - kids aged 6 and 9",
    },
    
    // Pending bookings
    {
      tourId: createdTours[3].id,
      userId: explorer4.id,
      date: new Date("2025-11-15"),
      numberOfGuests: 1,
      totalPrice: 5500,
      status: "PENDING" as const,
    },
    {
      tourId: createdTours[4].id,
      userId: explorer5.id,
      date: new Date("2025-11-18"),
      numberOfGuests: 2,
      totalPrice: 15000,
      status: "PENDING" as const,
    },
  ];

  for (const booking of bookings) {
    await prisma.booking.create({ data: booking });
  }

  console.log("✅ Created bookings");

  // Create reviews (only for completed bookings)
  const reviews = [
    {
      tourId: createdTours[0].id,
      userId: explorer1.id,
      rating: 5,
      comment:
        "Absolutely wonderful tour! Maria was so knowledgeable and took us to places we never would have found on our own. The stories about Zurich's history were fascinating. Highly recommended!",
    },
    {
      tourId: createdTours[1].id,
      userId: explorer2.id,
      rating: 5,
      comment:
        "An incredible culinary experience! Every stop was amazing and the wine pairings were perfect. Lisa knew so much about Swiss food culture. Worth every franc!",
    },
    {
      tourId: createdTours[2].id,
      userId: explorer3.id,
      rating: 5,
      comment:
        "Breathtaking views and a perfect combination of lake and mountain scenery. Hans was an excellent guide with great knowledge of the local nature. The weather was perfect too!",
    },
    {
      tourId: createdTours[4].id,
      userId: explorer4.id,
      rating: 5,
      comment:
        "My kids LOVED this workshop! We made delicious chocolates and learned so much. The instructor was patient and fun. We're still eating our creations!",
    },
    {
      tourId: createdTours[0].id,
      userId: explorer2.id,
      rating: 5,
      comment:
        "Great way to see the Old Town. Maria's passion for Zurich really shines through. The small group size made it feel very personal.",
    },
    {
      tourId: createdTours[1].id,
      userId: explorer3.id,
      rating: 4,
      comment:
        "Excellent food tour with high-quality tastings. Would have loved one more stop, but overall fantastic experience!",
    },
    {
      tourId: createdTours[2].id,
      userId: explorer1.id,
      rating: 5,
      comment:
        "The mountain views were spectacular! Hans timed everything perfectly for the best photo opportunities. A must-do in Zurich!",
    },
    {
      tourId: createdTours[4].id,
      userId: explorer5.id,
      rating: 5,
      comment:
        "Hands down the best chocolate workshop I've ever done. Professional, fun, and delicious!",
    },
    {
      tourId: createdTours[5].id,
      userId: explorer2.id,
      rating: 4,
      comment:
        "Great evening tour with beautiful photo opportunities. Thomas gave helpful photography tips. Would recommend bringing a tripod!",
    },
    {
      tourId: createdTours[3].id,
      userId: explorer4.id,
      rating: 5,
      comment:
        "The art museum tour was incredible! Learned so much about Swiss and international art. Highly recommend for art lovers!",
    },
  ];

  for (const review of reviews) {
    await prisma.review.create({ data: review });
  }

  console.log("✅ Created reviews");

  console.log("🎉 Seed completed successfully!");
}

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