/**
 * Bulk index all property listings into Meilisearch "listings" index.
 * Use for first-time sync or full re-index.
 *
 * Usage (from project root):
 *   npx ts-node --transpile-only src/scripts/bulkIndex.ts
 *   # or: pnpm run bulk-index
 */

import { createStrapi } from "@strapi/strapi";
import {
  getMeilisearchClient,
  listingToMeilisearchDoc,
  indexListings,
} from "../lib/meilisearch";

const BATCH_SIZE = 50;

async function main() {
  console.log("[bulkIndex] Loading Strapi...");
  const strapi = await createStrapi().load();

  if (!getMeilisearchClient()) {
    console.error(
      "[bulkIndex] Meilisearch not configured. Set MEILISEARCH_HOST and MEILISEARCH_MASTER_KEY in .env"
    );
    await strapi.destroy();
    process.exit(1);
  }

  try {
    console.log("[bulkIndex] Fetching all listings (properties)...");
    const entries = await strapi.entityService.findMany(
      "api::property.property",
      {
        populate: {
          location: { fields: ["name", "slug"] },
          cardImage: { fields: ["url"] },
        },
        publicationState: "live",
      }
    );

    const total = Array.isArray(entries) ? entries.length : 0;
    console.log(`[bulkIndex] Found ${total} listings. Indexing...`);

    if (total === 0) {
      console.log("[bulkIndex] Done. No listings to index.");
      await strapi.destroy();
      process.exit(0);
    }

    const docs = (Array.isArray(entries) ? entries : []).map((entry: any) =>
      listingToMeilisearchDoc(entry)
    );

    let indexed = 0;
    for (let i = 0; i < docs.length; i += BATCH_SIZE) {
      const batch = docs.slice(i, i + BATCH_SIZE);
      const ok = await indexListings(batch);
      if (ok) {
        indexed += batch.length;
        console.log(`[bulkIndex] Progress: ${indexed}/${total}`);
      } else {
        console.warn(`[bulkIndex] Batch failed at ${i}-${i + batch.length}`);
      }
    }

    console.log(`[bulkIndex] Done. Indexed ${indexed} listings into Meilisearch "listings" index.`);
  } catch (err) {
    console.error("[bulkIndex] Error:", err);
    process.exitCode = 1;
  } finally {
    await strapi.destroy();
  }
}

main();
