/**
 * Seed sample properties for the al Macron city test org so the
 * unified WhatsApp engine has real listings to return when the
 * customer asks for property viewings.
 */
import { config } from "dotenv";
config({ path: ".env.local" });

import { ConvexHttpClient } from "convex/browser";

const client = new ConvexHttpClient(process.env.NEXT_PUBLIC_CONVEX_URL!);

const ORG_ID = "td78hfqhx5n446n22hkhm8axh5835hy0";
const OWNER_ID = "h97ht1nxhkgzbt9e09k8kxfyr9826jsm";

const samples = [
  {
    titleEn: "2BR Apartment in The Pearl — Sea View",
    titleAr: "شقة غرفتين في اللؤلؤة — إطلالة بحرية",
    propertyType: "APARTMENT" as const,
    listingType: "RENT" as const,
    city: "Doha",
    district: "The Pearl",
    streetAddress: "Porto Arabia Tower 12, The Pearl-Qatar",
    buildingName: "Porto Arabia Tower 12",
    unitNumber: "1408",
    price: 9500,
    currency: "QAR" as const,
    bedrooms: 2,
    bathrooms: 2,
    builtUpArea: 120,
  },
  {
    titleEn: "2BR Apartment in West Bay — Corniche View",
    titleAr: "شقة غرفتين في ويست باي — إطلالة الكورنيش",
    propertyType: "APARTMENT" as const,
    listingType: "RENT" as const,
    city: "Doha",
    district: "West Bay",
    streetAddress: "Zig Zag Tower A, Al Corniche Street, West Bay",
    buildingName: "Zig Zag Tower A",
    unitNumber: "2205",
    price: 10000,
    currency: "QAR" as const,
    bedrooms: 2,
    bathrooms: 2,
    builtUpArea: 115,
  },
  {
    titleEn: "3BR Apartment in Lusail Marina",
    titleAr: "شقة ٣ غرف في لوسيل مارينا",
    propertyType: "APARTMENT" as const,
    listingType: "RENT" as const,
    city: "Lusail",
    district: "Marina District",
    streetAddress: "Marina Residence 7, Al Erkyah City, Lusail",
    buildingName: "Marina Residence 7",
    unitNumber: "903",
    price: 13500,
    currency: "QAR" as const,
    bedrooms: 3,
    bathrooms: 3,
    builtUpArea: 160,
  },
  {
    titleEn: "4BR Villa in Al Waab — Compound",
    titleAr: "فيلا ٤ غرف في الوعب — مجمع",
    propertyType: "COMPOUND_VILLA" as const,
    listingType: "RENT" as const,
    city: "Doha",
    district: "Al Waab",
    streetAddress: "Al Waab Family Compound, Al Waab Street, near Aspire Zone",
    buildingName: "Al Waab Family Compound",
    unitNumber: "Villa 14",
    price: 22000,
    currency: "QAR" as const,
    bedrooms: 4,
    bathrooms: 4,
    builtUpArea: 320,
  },
  {
    titleEn: "Studio Apartment in The Pearl — Furnished",
    titleAr: "شقة استوديو في اللؤلؤة — مفروشة",
    propertyType: "STUDIO" as const,
    listingType: "RENT" as const,
    city: "Doha",
    district: "The Pearl",
    streetAddress: "Viva Bahriya Tower 4, The Pearl-Qatar",
    buildingName: "Viva Bahriya Tower 4",
    unitNumber: "607",
    price: 6000,
    currency: "QAR" as const,
    bedrooms: 0,
    bathrooms: 1,
    builtUpArea: 55,
  },
  {
    titleEn: "5BR Villa in Al Gharafa — For Sale",
    titleAr: "فيلا ٥ غرف في الغرافة — للبيع",
    propertyType: "VILLA" as const,
    listingType: "SALE" as const,
    city: "Doha",
    district: "Al Gharafa",
    streetAddress: "Street 850, Villa 23, Al Gharafa",
    buildingName: "Private Villa",
    unitNumber: "23",
    price: 4200000,
    currency: "QAR" as const,
    bedrooms: 5,
    bathrooms: 5,
    builtUpArea: 450,
  },
];

(async () => {
  // First wipe any existing properties for this owner so we don't
  // accumulate duplicates when re-running the seeder after a schema
  // change (e.g. adding streetAddress).
  try {
    const existing = (await client.query(
      "real_estate/queries:getProperties" as unknown as never,
      { userId: OWNER_ID, limit: 100 } as unknown as never,
    )) as Array<{ _id: string; titleEn: string }> | null;

    if (Array.isArray(existing) && existing.length > 0) {
      console.log(`Wiping ${existing.length} existing properties...`);
      for (const p of existing) {
        try {
          await client.mutation(
            "real_estate/mutations:deleteProperty" as unknown as never,
            { id: p._id } as unknown as never,
          );
          console.log(`  🗑  ${p.titleEn}`);
        } catch (e) {
          console.log(`  ⚠️  Failed to delete ${p.titleEn}:`, (e as Error).message.substring(0, 80));
        }
      }
      console.log("");
    }
  } catch (e) {
    console.log("Wipe step skipped (query failed):", (e as Error).message.substring(0, 100));
  }

  let seeded = 0;
  let errors = 0;
  for (const p of samples) {
    try {
      await client.mutation(
        "real_estate/mutations:createProperty" as unknown as never,
        {
          userId: OWNER_ID,
          organizationId: ORG_ID,
          ...p,
        } as unknown as never,
      );
      seeded++;
      console.log(`  ✅ ${p.titleEn}`);
    } catch (e) {
      errors++;
      console.log(`  ❌ ${p.titleEn}:`, (e as Error).message.substring(0, 120));
    }
  }
  console.log(`\nSeeded ${seeded}/${samples.length} properties, ${errors} errors`);
})();
