import {CurrencyCode, LanguageCode, PrismaClient, TenantStatus, UserStatus, VehicleCategory} from "@prisma/client";
import {hashPassword} from "../src/lib/auth/password";

const prisma = new PrismaClient();

async function resetDatabase() {
  await prisma.rentalContract.deleteMany();
  await prisma.notificationDelivery.deleteMany();
  await prisma.notification.deleteMany();
  await prisma.refundTransaction.deleteMany();
  await prisma.paymentTransaction.deleteMany();
  await prisma.invoice.deleteMany();
  await prisma.bookingAddonItem.deleteMany();
  await prisma.bookingAddon.deleteMany();
  await prisma.bookingDriver.deleteMany();
  await prisma.booking.deleteMany();
  await prisma.maintenanceRecord.deleteMany();
  await prisma.vehicleAvailabilityBlock.deleteMany();
  await prisma.vehicleFeatureAssignment.deleteMany();
  await prisma.vehicleImage.deleteMany();
  await prisma.favoriteVehicle.deleteMany();
  await prisma.document.deleteMany();
  await prisma.vehicle.deleteMany();
  await prisma.branch.deleteMany();
  await prisma.customerProfile.deleteMany();
  await prisma.membership.deleteMany();
  await prisma.userPlatformRole.deleteMany();
  await prisma.account.deleteMany();
  await prisma.session.deleteMany();
  await prisma.auditLog.deleteMany();
  await prisma.contactInquiry.deleteMany();
  await prisma.savedSearch.deleteMany();
  await prisma.coupon.deleteMany();
  await prisma.tenantSetting.deleteMany();
  await prisma.tenant.deleteMany();
  await prisma.user.deleteMany();
  await prisma.vehicleModel.deleteMany();
  await prisma.vehicleBrand.deleteMany();
  await prisma.vehicleFeature.deleteMany();
  await prisma.platformSetting.deleteMany();
}

async function main() {
  await resetDatabase();

  const passwordHash = await hashPassword("Admin123!");

  // ─────────────────────────────────────────────────────────
  // Platform Settings
  // ─────────────────────────────────────────────────────────
  await prisma.platformSetting.create({
    data: {
      platformName: "Car Rental System",
      defaultLanguage: LanguageCode.EN,
      supportedLanguages: ["en", "ar"],
      defaultCurrency: CurrencyCode.USD,
      timezone: "UTC",
      contactEmail: "support@demo.local",
      contactPhone: "+1-555-100-1000"
    }
  });

  // ─────────────────────────────────────────────────────────
  // Vehicle Brands + Models
  // ─────────────────────────────────────────────────────────
  const toyota = await prisma.vehicleBrand.create({data: {name: "Toyota", slug: "toyota"}});
  const nissan = await prisma.vehicleBrand.create({data: {name: "Nissan", slug: "nissan"}});
  const bmw = await prisma.vehicleBrand.create({data: {name: "BMW", slug: "bmw"}});
  const mercedes = await prisma.vehicleBrand.create({data: {name: "Mercedes-Benz", slug: "mercedes-benz"}});
  const hyundai = await prisma.vehicleBrand.create({data: {name: "Hyundai", slug: "hyundai"}});

  const corolla = await prisma.vehicleModel.create({data: {brandId: toyota.id, name: "Corolla", slug: "corolla", category: VehicleCategory.SEDAN}});
  const camry = await prisma.vehicleModel.create({data: {brandId: toyota.id, name: "Camry", slug: "camry", category: VehicleCategory.SEDAN}});
  const rav4 = await prisma.vehicleModel.create({data: {brandId: toyota.id, name: "RAV4", slug: "rav4", category: VehicleCategory.SUV}});
  const fortuner = await prisma.vehicleModel.create({data: {brandId: toyota.id, name: "Fortuner", slug: "fortuner", category: VehicleCategory.SUV}});
  const land_cruiser = await prisma.vehicleModel.create({data: {brandId: toyota.id, name: "Land Cruiser", slug: "land-cruiser", category: VehicleCategory.SUV}});
  const sunny = await prisma.vehicleModel.create({data: {brandId: nissan.id, name: "Sunny", slug: "sunny", category: VehicleCategory.ECONOMY}});
  const xtrail = await prisma.vehicleModel.create({data: {brandId: nissan.id, name: "X-Trail", slug: "x-trail", category: VehicleCategory.SUV}});
  const patrol = await prisma.vehicleModel.create({data: {brandId: nissan.id, name: "Patrol", slug: "patrol", category: VehicleCategory.SUV}});
  const bwm5 = await prisma.vehicleModel.create({data: {brandId: bmw.id, name: "5 Series", slug: "5-series", category: VehicleCategory.LUXURY}});
  const eclass = await prisma.vehicleModel.create({data: {brandId: mercedes.id, name: "E-Class", slug: "e-class", category: VehicleCategory.LUXURY}});
  const tucson = await prisma.vehicleModel.create({data: {brandId: hyundai.id, name: "Tucson", slug: "tucson", category: VehicleCategory.SUV}});
  const accent = await prisma.vehicleModel.create({data: {brandId: hyundai.id, name: "Accent", slug: "accent", category: VehicleCategory.ECONOMY}});

  const gpsFeature = await prisma.vehicleFeature.create({data: {key: "gps", labelAr: "نظام ملاحة", labelEn: "GPS"}});
  const bluetoothFeature = await prisma.vehicleFeature.create({data: {key: "bluetooth", labelAr: "بلوتوث", labelEn: "Bluetooth"}});
  const acFeature = await prisma.vehicleFeature.create({data: {key: "ac", labelAr: "تكييف", labelEn: "Air Conditioning"}});
  const insuranceFeature = await prisma.vehicleFeature.create({data: {key: "insurance", labelAr: "تأمين شامل", labelEn: "Insurance Included"}});

  // ─────────────────────────────────────────────────────────
  // Super Admin
  // ─────────────────────────────────────────────────────────
  const superAdmin = await prisma.user.create({
    data: {
      name: "Platform Super Admin",
      firstName: "Platform",
      lastName: "Admin",
      email: "superadmin@demo.local",
      passwordHash,
      preferredLanguage: LanguageCode.EN,
      status: UserStatus.ACTIVE,
      platformRoles: {create: {role: "SUPER_ADMIN"}}
    }
  });

  // ─────────────────────────────────────────────────────────
  // Tenants
  // ─────────────────────────────────────────────────────────
  const tenantConfigs = [
    {
      name: "Swift Drive Rentals",
      slug: "swift-drive",
      email: "hello@swiftdrive.local",
      phone: "+971500000001",
      city: "Dubai",
      country: "UAE",
      timezone: "Asia/Dubai",
      currency: CurrencyCode.AED,
      language: LanguageCode.EN,
      bookingPrefix: "SDR",
      invoicePrefix: "INV-SDR",
      status: TenantStatus.ACTIVE,
      taxRate: 5,
      depositDefault: 1000
    },
    {
      name: "Desert Rides",
      slug: "desert-rides",
      email: "team@desertrides.local",
      phone: "+966500000002",
      city: "Riyadh",
      country: "Saudi Arabia",
      timezone: "Asia/Riyadh",
      currency: CurrencyCode.SAR,
      language: LanguageCode.AR,
      bookingPrefix: "DRC",
      invoicePrefix: "INV-DRC",
      status: TenantStatus.TRIAL,
      taxRate: 15,
      depositDefault: 800
    }
  ];

  for (const cfg of tenantConfigs) {
    const tenant = await prisma.tenant.create({
      data: {
        name: cfg.name,
        slug: cfg.slug,
        status: cfg.status,
        email: cfg.email,
        phone: cfg.phone,
        city: cfg.city,
        country: cfg.country,
        timezone: cfg.timezone,
        currency: cfg.currency,
        defaultLanguage: cfg.language,
        supportedLanguages: ["en", "ar"],
        bookingPrefix: cfg.bookingPrefix,
        invoicePrefix: cfg.invoicePrefix,
        taxRate: cfg.taxRate,
        isPublicListingEnabled: true,
        settings: {
          create: {
            bookingRequiresApproval: true,
            allowInstantBooking: false,
            minimumRentalHours: 24,
            maximumRentalDays: 30,
            defaultDepositAmount: cfg.depositDefault,
            cancellationWindowHours: 24,
            lateReturnFeePerHour: 25
          }
        }
      }
    });

    // ── Admin
    const admin = await prisma.user.create({
      data: {
        name: `${cfg.name} Admin`,
        firstName: cfg.slug === "swift-drive" ? "Ahmed" : "Mohammed",
        lastName: "Admin",
        email: `admin@${cfg.slug}.local`,
        passwordHash,
        preferredLanguage: cfg.language,
        status: UserStatus.ACTIVE,
        memberships: {create: {tenantId: tenant.id, role: "COMPANY_ADMIN", isDefault: true}}
      }
    });

    // ── Staff
    await prisma.user.create({
      data: {
        name: `${cfg.name} Staff`,
        firstName: cfg.slug === "swift-drive" ? "Sara" : "Fatima",
        lastName: "Staff",
        email: `staff@${cfg.slug}.local`,
        passwordHash,
        preferredLanguage: cfg.language,
        status: UserStatus.ACTIVE,
        memberships: {create: {tenantId: tenant.id, role: "COMPANY_STAFF", isDefault: true}}
      }
    });

    // ── Customers (3-4 per company)
    const customerData = [
      {first: "John", last: "Smith", email: `john@${cfg.slug}.local`, nationality: "USA", license: `DL-${cfg.slug.toUpperCase()}-001`, blacklisted: false},
      {first: "Maria", last: "Garcia", email: `maria@${cfg.slug}.local`, nationality: cfg.country, license: `DL-${cfg.slug.toUpperCase()}-002`, blacklisted: false},
      {first: "Omar", last: "Hassan", email: `omar@${cfg.slug}.local`, nationality: cfg.country, license: `DL-${cfg.slug.toUpperCase()}-003`, blacklisted: false},
      {first: "Bad", last: "Actor", email: `bad@${cfg.slug}.local`, nationality: "Unknown", license: `DL-${cfg.slug.toUpperCase()}-BAD`, blacklisted: true}
    ];

    const customerUsers: typeof admin[] = [];
    const customerProfiles: {id: string; userId: string}[] = [];

    for (const [ci, cdata] of customerData.entries()) {
      const cu = await prisma.user.create({
        data: {
          name: `${cdata.first} ${cdata.last}`,
          firstName: cdata.first,
          lastName: cdata.last,
          email: cdata.email,
          passwordHash,
          preferredLanguage: cfg.language,
          status: UserStatus.ACTIVE,
          memberships: {create: {tenantId: tenant.id, role: "CUSTOMER", isDefault: true}}
        }
      });
      const cp = await prisma.customerProfile.create({
        data: {
          tenantId: tenant.id,
          userId: cu.id,
          customerCode: `${cfg.bookingPrefix}-CUS-${String(ci + 1).padStart(3, "0")}`,
          nationality: cdata.nationality,
          city: cfg.city,
          country: cfg.country,
          driverLicenseNumber: cdata.license,
          driverLicenseExpiry: new Date("2028-12-31"),
          blacklisted: cdata.blacklisted
        }
      });
      customerUsers.push(cu);
      customerProfiles.push({id: cp.id, userId: cu.id});
    }

    // ── Branches
    const mainBranch = await prisma.branch.create({
      data: {
        tenantId: tenant.id,
        name: `${cfg.name} Main Branch`,
        code: `${cfg.bookingPrefix}-MAIN`,
        email: `main@${cfg.slug}.local`,
        phone: cfg.phone,
        city: cfg.city,
        country: cfg.country,
        addressLine1: "Central Business District",
        isActive: true
      }
    });

    const airportBranch = await prisma.branch.create({
      data: {
        tenantId: tenant.id,
        name: `${cfg.name} Airport Branch`,
        code: `${cfg.bookingPrefix}-AIR`,
        email: `airport@${cfg.slug}.local`,
        city: cfg.city,
        country: cfg.country,
        addressLine1: "Airport Road, Terminal 2",
        isActive: true
      }
    });

    // ── Fleet (8-10 vehicles per company)
    type VehicleSpec = {
      name: string; slug: string; brandId: string; modelId: string; year: number;
      plate: string; vin: string; color: string;
      category: VehicleCategory; transmission: string; fuelType: string;
      seats: number; doors: number; bags: number; mileage: number;
      dailyRate: number; weeklyRate: number; monthlyRate: number;
      depositAmount: number; status: string;
      airConditioning: boolean; hasGps: boolean; hasBluetooth: boolean; insuranceIncluded: boolean;
      featured: boolean; branchId: string; imageUrl: string;
    };

    const fleetSpecs: VehicleSpec[] = [
      {name: "Toyota Corolla SE", slug: `${cfg.slug}-corolla-se`, brandId: toyota.id, modelId: corolla.id, year: 2024, plate: `${cfg.bookingPrefix}-101`, vin: `${cfg.bookingPrefix}VIN101`, color: "White", category: VehicleCategory.SEDAN, transmission: "AUTOMATIC", fuelType: "PETROL", seats: 5, doors: 4, bags: 3, mileage: 12000, dailyRate: 180, weeklyRate: 1080, monthlyRate: 3600, depositAmount: cfg.depositDefault, status: "AVAILABLE", airConditioning: true, hasGps: true, hasBluetooth: true, insuranceIncluded: true, featured: true, branchId: mainBranch.id, imageUrl: "https://images.unsplash.com/photo-1549399542-7e3f8b79c341?w=800"},
      {name: "Toyota Camry XLE", slug: `${cfg.slug}-camry-xle`, brandId: toyota.id, modelId: camry.id, year: 2024, plate: `${cfg.bookingPrefix}-102`, vin: `${cfg.bookingPrefix}VIN102`, color: "Black", category: VehicleCategory.SEDAN, transmission: "AUTOMATIC", fuelType: "PETROL", seats: 5, doors: 4, bags: 4, mileage: 8000, dailyRate: 220, weeklyRate: 1320, monthlyRate: 4400, depositAmount: cfg.depositDefault + 200, status: "RENTED", airConditioning: true, hasGps: true, hasBluetooth: true, insuranceIncluded: true, featured: true, branchId: mainBranch.id, imageUrl: "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=800"},
      {name: "Toyota RAV4 AWD", slug: `${cfg.slug}-rav4-awd`, brandId: toyota.id, modelId: rav4.id, year: 2023, plate: `${cfg.bookingPrefix}-103`, vin: `${cfg.bookingPrefix}VIN103`, color: "Silver", category: VehicleCategory.SUV, transmission: "AUTOMATIC", fuelType: "HYBRID", seats: 5, doors: 4, bags: 4, mileage: 15000, dailyRate: 260, weeklyRate: 1560, monthlyRate: 5200, depositAmount: cfg.depositDefault + 400, status: "AVAILABLE", airConditioning: true, hasGps: true, hasBluetooth: true, insuranceIncluded: true, featured: true, branchId: mainBranch.id, imageUrl: "https://images.unsplash.com/photo-1625231340007-c0c3e3a43c0f?w=800"},
      {name: "Toyota Fortuner 4x4", slug: `${cfg.slug}-fortuner`, brandId: toyota.id, modelId: fortuner.id, year: 2024, plate: `${cfg.bookingPrefix}-104`, vin: `${cfg.bookingPrefix}VIN104`, color: "Pearl White", category: VehicleCategory.SUV, transmission: "AUTOMATIC", fuelType: "DIESEL", seats: 7, doors: 4, bags: 5, mileage: 5000, dailyRate: 320, weeklyRate: 1920, monthlyRate: 6400, depositAmount: cfg.depositDefault + 600, status: "AVAILABLE", airConditioning: true, hasGps: true, hasBluetooth: true, insuranceIncluded: true, featured: false, branchId: airportBranch.id, imageUrl: "https://images.unsplash.com/photo-1503376780353-7e6692767b70?w=800"},
      {name: "Toyota Land Cruiser V8", slug: `${cfg.slug}-land-cruiser`, brandId: toyota.id, modelId: land_cruiser.id, year: 2024, plate: `${cfg.bookingPrefix}-105`, vin: `${cfg.bookingPrefix}VIN105`, color: "Midnight Black", category: VehicleCategory.SUV, transmission: "AUTOMATIC", fuelType: "PETROL", seats: 7, doors: 4, bags: 6, mileage: 3000, dailyRate: 480, weeklyRate: 2880, monthlyRate: 9600, depositAmount: cfg.depositDefault + 1200, status: "MAINTENANCE", airConditioning: true, hasGps: true, hasBluetooth: true, insuranceIncluded: true, featured: true, branchId: mainBranch.id, imageUrl: "https://images.unsplash.com/photo-1605559424843-9e4c228bf1c2?w=800"},
      {name: "Nissan Sunny Economy", slug: `${cfg.slug}-sunny`, brandId: nissan.id, modelId: sunny.id, year: 2023, plate: `${cfg.bookingPrefix}-201`, vin: `${cfg.bookingPrefix}VIN201`, color: "Blue", category: VehicleCategory.ECONOMY, transmission: "AUTOMATIC", fuelType: "PETROL", seats: 5, doors: 4, bags: 2, mileage: 22000, dailyRate: 120, weeklyRate: 720, monthlyRate: 2400, depositAmount: cfg.depositDefault - 200, status: "AVAILABLE", airConditioning: true, hasGps: false, hasBluetooth: true, insuranceIncluded: false, featured: false, branchId: airportBranch.id, imageUrl: "https://images.unsplash.com/photo-1494976388531-d1058494cdd8?w=800"},
      {name: "Nissan X-Trail SV", slug: `${cfg.slug}-xtrail`, brandId: nissan.id, modelId: xtrail.id, year: 2024, plate: `${cfg.bookingPrefix}-202`, vin: `${cfg.bookingPrefix}VIN202`, color: "Deep Blue", category: VehicleCategory.SUV, transmission: "AUTOMATIC", fuelType: "PETROL", seats: 5, doors: 4, bags: 3, mileage: 9000, dailyRate: 240, weeklyRate: 1440, monthlyRate: 4800, depositAmount: cfg.depositDefault + 300, status: "AVAILABLE", airConditioning: true, hasGps: true, hasBluetooth: true, insuranceIncluded: true, featured: false, branchId: airportBranch.id, imageUrl: "https://images.unsplash.com/photo-1617720596960-93e5c2b65f34?w=800"},
      {name: "Nissan Patrol LE", slug: `${cfg.slug}-patrol`, brandId: nissan.id, modelId: patrol.id, year: 2024, plate: `${cfg.bookingPrefix}-203`, vin: `${cfg.bookingPrefix}VIN203`, color: "Grey", category: VehicleCategory.SUV, transmission: "AUTOMATIC", fuelType: "PETROL", seats: 8, doors: 4, bags: 7, mileage: 4000, dailyRate: 420, weeklyRate: 2520, monthlyRate: 8400, depositAmount: cfg.depositDefault + 1000, status: "AVAILABLE", airConditioning: true, hasGps: true, hasBluetooth: true, insuranceIncluded: true, featured: false, branchId: mainBranch.id, imageUrl: "https://images.unsplash.com/photo-1583121274602-3e2820c69888?w=800"},
      {name: "BMW 5 Series 530i", slug: `${cfg.slug}-bmw5`, brandId: bmw.id, modelId: bwm5.id, year: 2024, plate: `${cfg.bookingPrefix}-301`, vin: `${cfg.bookingPrefix}VIN301`, color: "Alpine White", category: VehicleCategory.LUXURY, transmission: "AUTOMATIC", fuelType: "PETROL", seats: 5, doors: 4, bags: 4, mileage: 6000, dailyRate: 550, weeklyRate: 3300, monthlyRate: 11000, depositAmount: cfg.depositDefault + 2000, status: "AVAILABLE", airConditioning: true, hasGps: true, hasBluetooth: true, insuranceIncluded: true, featured: true, branchId: mainBranch.id, imageUrl: "https://images.unsplash.com/photo-1555215695-3004980ad54e?w=800"},
      {name: "Mercedes E-Class 200", slug: `${cfg.slug}-eclass`, brandId: mercedes.id, modelId: eclass.id, year: 2024, plate: `${cfg.bookingPrefix}-302`, vin: `${cfg.bookingPrefix}VIN302`, color: "Obsidian Black", category: VehicleCategory.LUXURY, transmission: "AUTOMATIC", fuelType: "PETROL", seats: 5, doors: 4, bags: 3, mileage: 7000, dailyRate: 580, weeklyRate: 3480, monthlyRate: 11600, depositAmount: cfg.depositDefault + 2200, status: "AVAILABLE", airConditioning: true, hasGps: true, hasBluetooth: true, insuranceIncluded: true, featured: true, branchId: airportBranch.id, imageUrl: "https://images.unsplash.com/photo-1616788494672-ec7ca25fdda9?w=800"}
    ];

    const fleet: {id: string; dailyRate: {toNumber?: () => number} | number; depositAmount: {toNumber?: () => number} | number; name: string; plateNumber: string}[] = [];
    for (const spec of fleetSpecs) {
      const v = await prisma.vehicle.create({
        data: {
          tenantId: tenant.id,
          branchId: spec.branchId,
          brandId: spec.brandId,
          modelId: spec.modelId,
          name: spec.name,
          slug: spec.slug,
          year: spec.year,
          plateNumber: spec.plate,
          vin: spec.vin,
          color: spec.color,
          category: spec.category,
          transmission: spec.transmission as "AUTOMATIC" | "MANUAL",
          fuelType: spec.fuelType as "PETROL" | "DIESEL" | "HYBRID" | "ELECTRIC",
          seats: spec.seats,
          doors: spec.doors,
          bags: spec.bags,
          mileage: spec.mileage,
          dailyRate: spec.dailyRate,
          weeklyRate: spec.weeklyRate,
          monthlyRate: spec.monthlyRate,
          depositAmount: spec.depositAmount,
          status: spec.status as "AVAILABLE" | "RENTED" | "MAINTENANCE" | "RESERVED",
          airConditioning: spec.airConditioning,
          hasGps: spec.hasGps,
          hasBluetooth: spec.hasBluetooth,
          insuranceIncluded: spec.insuranceIncluded,
          featured: spec.featured,
          isPublic: true,
          descriptionEn: `Premium ${spec.category.toLowerCase()} vehicle, well maintained, ideal for city and long drives.`,
          descriptionAr: `مركبة ${spec.category === "ECONOMY" ? "اقتصادية" : spec.category === "SEDAN" ? "سيدان" : spec.category === "SUV" ? "دفع رباعي" : "فاخرة"} ممتازة.`,
          primaryImageUrl: spec.imageUrl,
          featureAssignments: {
            create: [
              ...(spec.hasGps ? [{tenantId: tenant.id, featureId: gpsFeature.id}] : []),
              {tenantId: tenant.id, featureId: bluetoothFeature.id},
              {tenantId: tenant.id, featureId: acFeature.id},
              ...(spec.insuranceIncluded ? [{tenantId: tenant.id, featureId: insuranceFeature.id}] : [])
            ]
          }
        }
      });
      fleet.push({id: v.id, dailyRate: v.dailyRate, depositAmount: v.depositAmount, name: v.name, plateNumber: v.plateNumber});
    }

    // ── Coupon
    await prisma.coupon.create({
      data: {
        tenantId: tenant.id,
        code: cfg.bookingPrefix === "SDR" ? "SWIFT20" : "DESERT15",
        type: "PERCENTAGE",
        value: cfg.bookingPrefix === "SDR" ? 20 : 15,
        usageLimit: 50,
        usedCount: 3,
        minimumAmount: 500,
        isActive: true,
        startsAt: new Date("2026-01-01"),
        endsAt: new Date("2026-12-31")
      }
    });

    // ── Bookings (5-6 per company with varied statuses)
    const bookingDefs = [
      // CONFIRMED (upcoming)
      {
        customerIdx: 0, vehicleIdx: 0, pickupBranchId: mainBranch.id, dropoffBranchId: airportBranch.id,
        pickupAt: new Date("2026-05-10T10:00:00.000Z"), dropoffAt: new Date("2026-05-14T10:00:00.000Z"),
        days: 4, status: "CONFIRMED", paidFraction: 0.3, suffix: "001"
      },
      // ACTIVE (currently rented)
      {
        customerIdx: 1, vehicleIdx: 1, pickupBranchId: mainBranch.id, dropoffBranchId: mainBranch.id,
        pickupAt: new Date("2026-04-28T09:00:00.000Z"), dropoffAt: new Date("2026-05-02T09:00:00.000Z"),
        days: 4, status: "ACTIVE", paidFraction: 1, suffix: "002"
      },
      // PENDING_APPROVAL
      {
        customerIdx: 2, vehicleIdx: 2, pickupBranchId: airportBranch.id, dropoffBranchId: airportBranch.id,
        pickupAt: new Date("2026-05-20T14:00:00.000Z"), dropoffAt: new Date("2026-05-25T14:00:00.000Z"),
        days: 5, status: "PENDING_APPROVAL", paidFraction: 0, suffix: "003"
      },
      // COMPLETED
      {
        customerIdx: 0, vehicleIdx: 5, pickupBranchId: airportBranch.id, dropoffBranchId: mainBranch.id,
        pickupAt: new Date("2026-04-01T10:00:00.000Z"), dropoffAt: new Date("2026-04-05T10:00:00.000Z"),
        days: 4, status: "COMPLETED", paidFraction: 1, suffix: "004"
      },
      // CANCELLED
      {
        customerIdx: 1, vehicleIdx: 6, pickupBranchId: mainBranch.id, dropoffBranchId: mainBranch.id,
        pickupAt: new Date("2026-03-15T10:00:00.000Z"), dropoffAt: new Date("2026-03-18T10:00:00.000Z"),
        days: 3, status: "CANCELLED", paidFraction: 0, suffix: "005"
      },
      // CONFIRMED — overdue (return date passed, still not returned for monitoring demo)
      {
        customerIdx: 2, vehicleIdx: 3, pickupBranchId: airportBranch.id, dropoffBranchId: airportBranch.id,
        pickupAt: new Date("2026-04-20T08:00:00.000Z"), dropoffAt: new Date("2026-04-25T08:00:00.000Z"),
        days: 5, status: "ACTIVE", paidFraction: 0.5, suffix: "006"
      }
    ];

    for (const bDef of bookingDefs) {
      const veh = fleet[bDef.vehicleIdx];
      const dailyRate = typeof veh.dailyRate === "object" && veh.dailyRate && "toNumber" in veh.dailyRate
        ? (veh.dailyRate as {toNumber: () => number}).toNumber()
        : Number(veh.dailyRate);
      const depositAmt = typeof veh.depositAmount === "object" && veh.depositAmount && "toNumber" in veh.depositAmount
        ? (veh.depositAmount as {toNumber: () => number}).toNumber()
        : Number(veh.depositAmount);
      const subtotal = bDef.days * dailyRate;
      const taxAmount = Math.round(subtotal * (cfg.taxRate / 100));
      const totalAmount = subtotal + taxAmount;
      const paidAmount = Math.round(totalAmount * bDef.paidFraction);

      const cProfile = customerProfiles[bDef.customerIdx];
      const cUser = customerUsers[bDef.customerIdx];

      const booking = await prisma.booking.create({
        data: {
          tenantId: tenant.id,
          bookingNumber: `${cfg.bookingPrefix}-${bDef.suffix}`,
          source: "TENANT_DASHBOARD",
          status: bDef.status as "CONFIRMED" | "ACTIVE" | "PENDING_APPROVAL" | "COMPLETED" | "CANCELLED",
          customerUserId: cUser.id,
          customerProfileId: cProfile.id,
          vehicleId: veh.id,
          pickupBranchId: bDef.pickupBranchId,
          dropoffBranchId: bDef.dropoffBranchId,
          pickupAt: bDef.pickupAt,
          dropoffAt: bDef.dropoffAt,
          rentalDays: bDef.days,
          dailyRate,
          subtotal,
          taxAmount,
          depositAmount: depositAmt,
          totalAmount,
          paidAmount,
          remainingAmount: totalAmount - paidAmount,
          currency: cfg.currency,
          confirmedAt: bDef.status !== "PENDING_APPROVAL" ? new Date() : null,
          actualPickupAt: ["ACTIVE", "COMPLETED"].includes(bDef.status) ? bDef.pickupAt : null,
          actualDropoffAt: bDef.status === "COMPLETED" ? bDef.dropoffAt : null,
          completedAt: bDef.status === "COMPLETED" ? bDef.dropoffAt : null,
          cancelledAt: bDef.status === "CANCELLED" ? new Date() : null,
          cancelReason: bDef.status === "CANCELLED" ? "Customer request" : null,
          createdById: admin.id
        }
      });

      if (["CONFIRMED", "ACTIVE", "COMPLETED"].includes(bDef.status)) {
        const invoice = await prisma.invoice.create({
          data: {
            tenantId: tenant.id,
            bookingId: booking.id,
            invoiceNumber: `${cfg.invoicePrefix}-${bDef.suffix}`,
            status: bDef.status === "COMPLETED" ? "PAID" : paidAmount >= totalAmount ? "PAID" : "ISSUED",
            issueDate: booking.confirmedAt ?? new Date(),
            dueDate: new Date(bDef.pickupAt.getTime() + 7 * 24 * 60 * 60 * 1000),
            subtotal,
            taxAmount,
            totalAmount,
            paidAmount,
            currency: cfg.currency
          }
        });

        if (paidAmount > 0) {
          await prisma.paymentTransaction.create({
            data: {
              tenantId: tenant.id,
              bookingId: booking.id,
              invoiceId: invoice.id,
              customerUserId: cUser.id,
              status: "PAID",
              method: "CARD",
              provider: "demo-gateway",
              providerReference: `${cfg.slug}-PAY-${bDef.suffix}`,
              amount: paidAmount,
              currency: cfg.currency,
              paidAt: new Date()
            }
          });
        }

        if (bDef.status !== "PENDING_APPROVAL") {
          await prisma.rentalContract.create({
            data: {
              tenantId: tenant.id,
              bookingId: booking.id,
              contractNumber: `${cfg.bookingPrefix}-CTR-${bDef.suffix}`,
              customerName: `${customerData[bDef.customerIdx].first} ${customerData[bDef.customerIdx].last}`,
              customerPhone: `+${cfg.country === "UAE" ? "971" : "966"}50${bDef.suffix}`,
              customerIdNumber: cProfile.id.slice(0, 8).toUpperCase(),
              licenseNumber: customerData[bDef.customerIdx].license,
              licenseExpiry: new Date("2028-12-31"),
              vehiclePlate: veh.plateNumber,
              vehicleName: veh.name,
              pickupLocation: `${cfg.name} Main Branch`,
              dropoffLocation: `${cfg.name} Airport Branch`,
              pickupDate: bDef.pickupAt,
              dropoffDate: bDef.dropoffAt,
              dailyRate,
              totalAmount,
              depositAmount: depositAmt,
              insuranceIncluded: true,
              status: bDef.status === "COMPLETED" ? "COMPLETED" : bDef.status === "ACTIVE" ? "ACTIVE" : "ACTIVE",
              signedAt: booking.confirmedAt ?? new Date(),
              createdById: admin.id,
              terms: "Standard rental terms and conditions apply. The vehicle must be returned in the same condition as received.",
              notes: `Demo contract for booking ${booking.bookingNumber}`
            }
          });
        }
      }
    }

    await prisma.auditLog.createMany({
      data: [
        {tenantId: tenant.id, userId: admin.id, action: "CREATE", entityType: "Tenant", entityId: tenant.id},
        {tenantId: tenant.id, userId: admin.id, action: "CREATE", entityType: "Fleet", entityId: fleet[0].id}
      ]
    });
  }

  console.log("\n=== Seed Complete ===");
  console.log(`Super Admin:          superadmin@demo.local / Admin123!`);
  console.log(`Swift Drive Admin:     admin@swift-drive.local / Admin123!`);
  console.log(`Swift Drive Staff:     staff@swift-drive.local / Admin123!`);
  console.log(`Swift Drive Customer:  john@swift-drive.local / Admin123!`);
  console.log(`Desert Rides Admin:    admin@desert-rides.local / Admin123!`);
  console.log(`Desert Rides Staff:    staff@desert-rides.local / Admin123!`);
  console.log(`Desert Rides Customer: john@desert-rides.local / Admin123!`);
  console.log("====================\n");
}

main()
  .catch((error) => {
    console.error(error);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
