/**
 * Configure the Meilisearch "listings" index settings.
 * Run after the Meilisearch client is set up (env: MEILISEARCH_HOST, MEILISEARCH_MASTER_KEY).
 *
 * Usage (from project root):
 *   npx ts-node --transpile-only src/scripts/configureMeilisearch.ts
 *   # or: pnpm run configure-meilisearch
 */

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

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

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

  const indexName = getListingsIndexName();
  console.log(`[configureMeilisearch] Configuring index "${indexName}"...`);

  try {
    const index = client.index(indexName);

    // Searchable: fields used for full-text search (order = ranking priority)
    await index.updateSearchableAttributes([
      "title",
      "slug",
      "location",
      "category",
    ]);
    console.log("[configureMeilisearch]   searchableAttributes: title, slug, location, category");

    // Filterable: for faceted filters
    await index.updateFilterableAttributes([
      "category",
      "typeSlugs",
      "status",
      "location",
      "locationSlug",
      "price",
      "area",
    ]);
    console.log("[configureMeilisearch]   filterableAttributes: category, typeSlugs, status, location, locationSlug, price, area");

    // Sortable: for ordering results
    await index.updateSortableAttributes([
      "title",
      "price",
      "area",
      "status",
      "statusPriority",
    ]);
    console.log(
      "[configureMeilisearch]   sortableAttributes: title, price, area, status, statusPriority"
    );

    console.log("[configureMeilisearch] Done. Index settings updated.");
  } catch (err) {
    console.error("[configureMeilisearch] Error:", err);
    process.exitCode = 1;
  } finally {
    await strapi.destroy();
  }
}

main();
