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

const prisma = new PrismaClient();

async function main() {
  const adminEmail = "admin@ywyw.com";
  const customerEmail = "cust@ywyw.com";

  const passwordHash = await bcrypt.hash("Dev1234#", 10);

  const admin = await prisma.user.upsert({
    where: { email: adminEmail },
    update: {},
    create: {
      email: adminEmail,
      name: "Admin User",
      role: "ADMIN",
      firstName: "Admin",
      lastName: "User",
      gender: "OTHER",
      emailVerified: true,
      forcePasswordReset: false,
      isActive: true,
    },
  });

  await prisma.credential.upsert({
    where: { userId: admin.id },
    update: { password: passwordHash },
    create: { userId: admin.id, password: passwordHash },
  });

  console.log("✅ Admin user created:", adminEmail);

  const customer = await prisma.user.upsert({
    where: { email: customerEmail },
    update: {},
    create: {
      email: customerEmail,
      name: "Customer User",
      role: "USER",
      firstName: "Customer",
      lastName: "User",
      gender: "OTHER",
      emailVerified: true,
      forcePasswordReset: false,
      isActive: true,
    },
  });

  await prisma.credential.upsert({
    where: { userId: customer.id },
    update: { password: passwordHash },
    create: { userId: customer.id, password: passwordHash },
  });

  console.log("✅ Customer user created:", customerEmail);

  const existingWebinars = await prisma.webinar.count();
  if (existingWebinars === 0) {
    const now = Date.now();
    const sample = [
      {
        title: "Estate Planning Fundamentals",
        description: "Learn the foundations of estate planning, wills, and trusts.",
        speaker: "Emily Roberts",
        startAt: new Date(now + 7 * 86400000),
        duration: 90,
        bannerUrl: null,
        category: "Basics",
        visibility: "PUBLIC",
        isActive: true,
        capacity: 50,
        priceCents: 0,
        learningPoints: [
          "Understanding the basics of wills and trusts",
          "Key differences between revocable and irrevocable trusts",
          "Common estate planning mistakes to avoid",
          "When to update your estate plan",
        ],
        meetingInfo: {},
      },
      {
        title: "Avoiding Probate: Strategies & Solutions",
        description: "Practical strategies to reduce or avoid probate delays.",
        speaker: "David Martinez",
        startAt: new Date(now + 10 * 86400000),
        duration: 75,
        bannerUrl: null,
        category: "Planning",
        visibility: "PUBLIC",
        isActive: true,
        capacity: 60,
        priceCents: 0,
        learningPoints: [
          "How probate works and why it can be costly",
          "Living trusts as probate avoidance tools",
          "Joint ownership strategies",
          "Beneficiary designations and their importance",
        ],
        meetingInfo: {},
      },
      {
        title: "Tax-Efficient Wealth Transfer",
        description: "Minimize taxes when transferring assets to heirs.",
        speaker: "Susan Chen",
        startAt: new Date(now + 14 * 86400000),
        duration: 60,
        bannerUrl: null,
        category: "Advanced",
        visibility: "PUBLIC",
        isActive: true,
        capacity: 40,
        priceCents: 0,
        learningPoints: [
          "Federal and state estate tax basics",
          "Gift tax exclusions and lifetime exemptions",
          "Charitable giving strategies",
          "Generation-skipping transfer tax considerations",
        ],
        meetingInfo: {},
      },
    ];

    for (const w of sample) {
      await prisma.webinar.create({ data: w });
    }

    console.log(`✅ Created ${sample.length} sample webinars`);
  } else {
    console.log(`ℹ️  Skipped webinar seeding - ${existingWebinars} already exist`);
  }

  const existingRegistrations = await prisma.webinarRegistration.count();
  if (existingRegistrations === 0) {
    const webinars = await prisma.webinar.findMany({ take: 2 });
    if (webinars.length >= 2) {
      await prisma.webinarRegistration.create({
        data: {
          userId: customer.id,
          webinarId: webinars[0].id,
          status: "CONFIRMED",
        },
      });

      await prisma.webinarRegistration.create({
        data: {
          userId: customer.id,
          webinarId: webinars[1].id,
          status: "CONFIRMED",
        },
      });

      console.log("✅ Created sample registrations for customer");
    }
  } else {
    console.log(`ℹ️  Skipped registration seeding - ${existingRegistrations} already exist`);
  }
}

main()
  .then(async () => {
    await prisma.$disconnect();
    console.log("✅ Seeding completed successfully");
  })
  .catch(async (e) => {
    console.error("❌ Seeding failed:", e);
    await prisma.$disconnect();
    process.exit(1);
  });
