/**
 * Inspect Sep 1–4 duplicate bookings before delete.
 * Run: npx tsx --env-file=.env scripts/inspect-dup-bookings.ts
 */
import { connectDb, disconnectDb } from "../src/db/mongoose";
import { Booking, Property, User } from "../src/db/models";

async function main() {
  await connectDb();

  const bookings = await Booking.find({
    checkIn: { $gte: new Date("2026-09-01T00:00:00.000Z"), $lt: new Date("2026-09-02T00:00:00.000Z") },
    checkOut: { $gte: new Date("2026-09-04T00:00:00.000Z"), $lt: new Date("2026-09-05T00:00:00.000Z") },
    status: { $in: ["WAITING_OWNER", "CONFIRMED", "PENDING_PAYMENT"] },
  }).lean();

  // Also match by exact known ids / property from diagnosis
  const byProperty = await Booking.find({
    propertyId: "cmrnmicot6f4cf02b41b43f9ac58d",
    status: "WAITING_OWNER",
  }).lean();

  const ids = new Set([
    ...bookings.map((b) => String(b._id)),
    ...byProperty.map((b) => String(b._id)),
  ]);

  const all = await Booking.find({ _id: { $in: [...ids] } }).lean();

  console.log(`candidates=${all.length}`);
  for (const b of all) {
    const customer = await User.findById(b.customerId)
      .select({ email: 1, fullName: 1, role: 1, createdAt: 1 })
      .lean();
    const owner = await User.findById(b.ownerId)
      .select({ email: 1, fullName: 1, role: 1 })
      .lean();
    const prop = await Property.findById(b.propertyId)
      .select({ titleAr: 1, titleEn: 1 })
      .lean();

    console.log(
      JSON.stringify(
        {
          bookingId: b._id,
          status: b.status,
          paymentStatus: (b as { payment?: { status?: string } }).payment?.status,
          checkIn: b.checkIn,
          checkOut: b.checkOut,
          totalTnd: b.totalTnd,
          totalLyd: b.totalLyd,
          createdAt: b.createdAt,
          propertyId: b.propertyId,
          propertyTitle: prop?.titleAr || prop?.titleEn,
          customer: customer
            ? { id: customer._id, email: customer.email, fullName: customer.fullName, role: customer.role }
            : null,
          owner: owner
            ? { id: owner._id, email: owner.email, fullName: owner.fullName, role: owner.role }
            : null,
        },
        null,
        2,
      ),
    );
  }

  await disconnectDb();
}

main().catch(async (e) => {
  console.error(e);
  await disconnectDb();
  process.exit(1);
});
