#!/usr/bin/env tsx
/**
 * WhatsApp Sector Switcher
 *
 * Flips a test organization from one sector to another, wiping all stale
 * state so each sector can be tested cleanly from a physical WhatsApp
 * device.
 *
 * What it does:
 *   1. Updates org.industry + org.sector
 *   2. Hard-deletes all existing workflows for the org
 *   3. Re-seeds sector default workflows for the new sector
 *   4. Clears all conversations + messages for the org (optional)
 *   5. Clears language preferences for the test phone (optional)
 *
 * Usage:
 *   npx tsx scripts/switch-sector.ts <org-id> <industry> [--reset-conversation=<phone>]
 *
 * Examples:
 *   # Switch to retail, keep existing conversation history
 *   npx tsx scripts/switch-sector.ts td7333140ae0h2y5t245wn9t8n84a5re retail-services
 *
 *   # Switch to restaurant, wipe conversation for +97455512345 so greeting plays again
 *   npx tsx scripts/switch-sector.ts td7333140ae0h2y5t245wn9t8n84a5re restaurants-cafes --reset-conversation=+97455512345
 *
 *   # Switch to real estate (will use RE webhook, not unified Twilio)
 *   npx tsx scripts/switch-sector.ts td7333140ae0h2y5t245wn9t8n84a5re property-facilities --reset-conversation=+97455512345
 *
 * Valid industry keys (see lib/config/industry-sector-map.ts):
 *   Health: healthcare, dental, physio, labs-diagnostics, telehealth, optometry, pharmacy
 *   Beauty: beauty-wellness, aesthetics, medical-spas
 *   Food:   food-hospitality, restaurants-cafes, hotels-accommodation
 *   Retail: retail-services, other
 *   Property: property-facilities
 *   Mobility: mobility-industry, vehicle-rental
 *   Home:   home-services-trades
 *   Education: education, sports-academies
 *   Events: events-venues
 *   Pet:    pet-services, vet
 *   Nonprofit: nonprofit-community
 *   Public: public-sector
 */

import { config } from "dotenv";
config({ path: ".env.local" });

import { ConvexHttpClient } from "convex/browser";
import {
  getSectorForIndustry,
  INDUSTRY_TO_SECTOR,
} from "../lib/config/industry-sector-map";

interface OrgDoc {
  _id: string;
  name?: string;
  industry?: string;
  sector?: string;
  twilioWhatsappNumber?: string;
  whatsappPhoneNumberId?: string;
}

interface ConversationDoc {
  _id: string;
  userPhone?: string;
}

interface WorkflowDoc {
  _id: string;
  name: string;
}

async function main() {
  const [orgId, industry, ...rest] = process.argv.slice(2);

  if (!orgId || !industry) {
    console.error(
      "Usage: npx tsx scripts/switch-sector.ts <org-id> <industry> [--reset-conversation=<phone>]",
    );
    process.exit(1);
  }

  if (!(industry in INDUSTRY_TO_SECTOR)) {
    console.error(`❌ Unknown industry: "${industry}"`);
    console.error(
      `Valid keys: ${Object.keys(INDUSTRY_TO_SECTOR).join(", ")}`,
    );
    process.exit(1);
  }

  const resetConvArg = rest.find((a) => a.startsWith("--reset-conversation="));
  const resetPhone = resetConvArg?.split("=")[1];

  const convexUrl = process.env.NEXT_PUBLIC_CONVEX_URL;
  if (!convexUrl) {
    console.error("❌ NEXT_PUBLIC_CONVEX_URL not set in .env.local");
    process.exit(1);
  }

  const client = new ConvexHttpClient(convexUrl);
  const sector = getSectorForIndustry(industry);

  console.log("┌─────────────────────────────────────────────────");
  console.log(`│ 🔄 Sector Switcher`);
  console.log(`│ Org:      ${orgId}`);
  console.log(`│ Industry: ${industry}`);
  console.log(`│ Sector:   ${sector}`);
  console.log(
    `│ Reset:    ${resetPhone ? `conversation for ${resetPhone}` : "keep existing history"}`,
  );
  console.log("└─────────────────────────────────────────────────");
  console.log("");

  // ── 1. Verify org exists ───────────────────────────────
  console.log("1️⃣  Looking up organization...");
  const org = (await client.query(
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    "organizations/queries:getOrganizationByAnyId" as any,
    { organizationId: orgId },
  )) as OrgDoc | null;

  if (!org) {
    console.error(`❌ Organization not found: ${orgId}`);
    process.exit(1);
  }

  console.log(`   ✅ Found: "${org.name}"`);
  console.log(`   Previous industry: ${org.industry ?? "(none)"}`);
  console.log(`   Previous sector:   ${org.sector ?? "(none)"}`);
  if (org.twilioWhatsappNumber) {
    console.log(`   Twilio number:     ${org.twilioWhatsappNumber}`);
  }
  console.log("");

  // ── 2. Update industry + sector ────────────────────────
  console.log("2️⃣  Updating industry + sector...");
  await client.mutation(
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    "organizations/mutations:updateOrganizationNoAuth" as any,
    { organizationId: orgId, industry, sector },
  );
  console.log(`   ✅ Set industry="${industry}", sector="${sector}"`);
  console.log("");

  // ── 3. Wipe existing workflows ─────────────────────────
  console.log("3️⃣  Wiping existing workflows...");
  const wipeResult = (await client.mutation(
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    "whatsapp/workflows:hardDeleteAllForOrg" as any,
    { organizationId: orgId },
  )) as { deleted: number };
  console.log(`   ✅ Deleted ${wipeResult.deleted} old workflow(s)`);
  console.log("");

  // ── 4. Re-seed sector default workflows ────────────────
  console.log(`4️⃣  Seeding default workflows for sector "${sector}"...`);
  const { seedDefaultWorkflows } = await import(
    "../lib/services/workflow-seeder.service"
  );
  const seedResult = await seedDefaultWorkflows(orgId, industry);
  console.log(
    `   ✅ Seeded ${seedResult.seeded} workflow(s), ${seedResult.errors} error(s)`,
  );

  // List what got seeded
  const seeded = (await client.query(
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    "whatsapp/workflows:listWorkflows" as any,
    { organizationId: orgId, activeOnly: true },
  )) as WorkflowDoc[];
  if (Array.isArray(seeded) && seeded.length > 0) {
    console.log(`   Workflows now active:`);
    for (const wf of seeded) {
      console.log(`     • ${wf.name}`);
    }
  }
  console.log("");

  // ── 5. Optionally wipe conversation + language pref ────
  if (resetPhone) {
    console.log(
      `5️⃣  Wiping conversation + language preference for ${resetPhone}...`,
    );

    // Find all conversations for this org+phone
    const convs = (await client.query(
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      "whatsapp/queries:getOrgConversations" as any,
      { organizationId: orgId, userPhone: resetPhone, limit: 100 },
    )) as ConversationDoc[];

    let deletedConvs = 0;
    if (Array.isArray(convs)) {
      for (const conv of convs) {
        try {
          await client.mutation(
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            "whatsapp/mutations:deleteOrgConversation" as any,
            { id: conv._id },
          );
          deletedConvs++;
        } catch (error) {
          console.warn(`   ⚠️  Failed to delete conversation ${conv._id}`, error);
        }
      }
    }
    console.log(`   ✅ Deleted ${deletedConvs} conversation(s) + all messages`);

    // Clear language preference
    try {
      const { deleteLanguagePreference } = await import(
        "../lib/services/whatsapp-language.service"
      );
      await deleteLanguagePreference(orgId, resetPhone);
      console.log(`   ✅ Cleared stored language preference`);
    } catch (error) {
      console.warn(`   ⚠️  Failed to clear language preference`, error);
    }
    console.log("");
  }

  // ── Done ───────────────────────────────────────────────
  console.log("┌─────────────────────────────────────────────────");
  console.log(`│ ✅ Sector switch complete`);
  console.log(`│`);
  console.log(`│ Next: send a WhatsApp message from ${resetPhone ?? "your test phone"}`);
  console.log(`│ to ${org.twilioWhatsappNumber ?? "<your Twilio sandbox number>"}`);
  console.log(`│`);
  console.log(
    `│ Webhook: ${sector === "property_facilities" ? "/api/webhooks/twilio-whatsapp-re" : "/api/webhooks/twilio-whatsapp"}`,
  );
  console.log("└─────────────────────────────────────────────────");
}

main().catch((err) => {
  console.error("❌ Script failed:", err);
  process.exit(1);
});
