#!/usr/bin/env npx tsx
/**
 * Wave 1 Migration Verification Script
 *
 * Queries the Convex dev deployment to verify that migrated data
 * from reviews, review_requests, review_widget_settings, and
 * review_question_templates landed correctly.
 *
 * Usage: npx tsx scripts/verify-wave1-convex.ts
 */

import { ConvexHttpClient } from "convex/browser";
import { api } from "../convex/_generated/api";

const CONVEX_URL = "https://tacit-chinchilla-978.convex.cloud";
const USER_ID = "qaa537hq8ko9v1yfhnfmbov2";

// Expected counts (from Prisma source of truth)
const EXPECTED = {
  reviews: 3,
  reviewRequests: 12,
  widgetSettings: 1, // getWidgetSettings returns a single object or null
  questionTemplates: 1,
};

const client = new ConvexHttpClient(CONVEX_URL);

async function main() {
  console.log("=".repeat(60));
  console.log("  Wave 1 Migration Verification");
  console.log("=".repeat(60));
  console.log(`  Convex URL : ${CONVEX_URL}`);
  console.log(`  userId     : ${USER_ID}`);
  console.log("");

  let allPassed = true;

  // 1. Reviews
  try {
    const reviews = await client.query(api.reviews.queries.getReviews, {
      userId: USER_ID,
    });
    const count = Array.isArray(reviews) ? reviews.length : 0;
    const pass = count === EXPECTED.reviews;
    if (!pass) allPassed = false;
    console.log(
      `  [${pass ? "PASS" : "FAIL"}] reviews: ${count} (expected ${EXPECTED.reviews})`
    );
    if (Array.isArray(reviews) && reviews.length > 0) {
      for (const r of reviews) {
        console.log(
          `         - ${r.customerName} | ${r.platform} | rating=${r.rating} | lang=${r.language}`
        );
      }
    }
  } catch (err) {
    allPassed = false;
    console.log(`  [FAIL] reviews: ERROR - ${err instanceof Error ? err.message : err}`);
  }

  console.log("");

  // 2. Review Requests
  try {
    const requests = await client.query(api.reviews.queries.getReviewRequests, {
      userId: USER_ID,
    });
    const count = Array.isArray(requests) ? requests.length : 0;
    const pass = count === EXPECTED.reviewRequests;
    if (!pass) allPassed = false;
    console.log(
      `  [${pass ? "PASS" : "FAIL"}] review_requests: ${count} (expected ${EXPECTED.reviewRequests})`
    );
    if (Array.isArray(requests) && requests.length > 0) {
      // Show status distribution
      const byStatus: Record<string, number> = {};
      const byChannel: Record<string, number> = {};
      for (const r of requests) {
        byStatus[r.status] = (byStatus[r.status] ?? 0) + 1;
        byChannel[r.channel] = (byChannel[r.channel] ?? 0) + 1;
      }
      console.log(`         by status : ${JSON.stringify(byStatus)}`);
      console.log(`         by channel: ${JSON.stringify(byChannel)}`);
    }
  } catch (err) {
    allPassed = false;
    console.log(
      `  [FAIL] review_requests: ERROR - ${err instanceof Error ? err.message : err}`
    );
  }

  console.log("");

  // 3. Widget Settings
  try {
    const settings = await client.query(api.reviews.queries.getWidgetSettings, {
      userId: USER_ID,
    });
    // getWidgetSettings returns a single object or null (uses .unique())
    const found = settings != null ? 1 : 0;
    const pass = found === EXPECTED.widgetSettings;
    if (!pass) allPassed = false;
    console.log(
      `  [${pass ? "PASS" : "FAIL"}] review_widget_settings: ${found} (expected ${EXPECTED.widgetSettings})`
    );
    if (settings) {
      console.log(
        `         businessName: ${settings.businessName ?? "(not set)"} | primaryColor: ${settings.primaryColor} | showPoweredBy: ${settings.showPoweredBy}`
      );
    }
  } catch (err) {
    allPassed = false;
    console.log(
      `  [FAIL] review_widget_settings: ERROR - ${err instanceof Error ? err.message : err}`
    );
  }

  console.log("");

  // 4. Question Templates
  try {
    const templates = await client.query(
      api.reviews.queries.getQuestionTemplates,
      { userId: USER_ID }
    );
    const count = Array.isArray(templates) ? templates.length : 0;
    const pass = count === EXPECTED.questionTemplates;
    if (!pass) allPassed = false;
    console.log(
      `  [${pass ? "PASS" : "FAIL"}] review_question_templates: ${count} (expected ${EXPECTED.questionTemplates})`
    );
    if (Array.isArray(templates) && templates.length > 0) {
      for (const t of templates) {
        const qCount = Array.isArray(t.questions) ? t.questions.length : 0;
        console.log(
          `         industry: ${t.industry} | questions: ${qCount} | isDefault: ${t.isDefault}`
        );
      }
    }
  } catch (err) {
    allPassed = false;
    console.log(
      `  [FAIL] review_question_templates: ERROR - ${err instanceof Error ? err.message : err}`
    );
  }

  console.log("");

  // Bonus: Review Stats (exercises the aggregation query)
  try {
    const stats = await client.query(api.reviews.queries.getReviewStats, {
      userId: USER_ID,
    });
    console.log("  [INFO] Review Stats (aggregation check):");
    console.log(`         total: ${stats.total} | avgRating: ${stats.averageRating} | responseRate: ${stats.responseRate}%`);
    console.log(`         distribution: ${JSON.stringify(stats.distribution)}`);
    console.log(`         byPlatform: ${JSON.stringify(stats.byPlatform)}`);
  } catch (err) {
    console.log(`  [WARN] getReviewStats: ${err instanceof Error ? err.message : err}`);
  }

  console.log("");

  // Bonus: Review Request Stats
  try {
    const reqStats = await client.query(
      api.reviews.queries.getReviewRequestStats,
      { userId: USER_ID }
    );
    console.log("  [INFO] Review Request Stats (aggregation check):");
    console.log(`         total: ${reqStats.total} | completionRate: ${reqStats.completionRate}%`);
    console.log(`         byStatus: ${JSON.stringify(reqStats.byStatus)}`);
    console.log(`         byChannel: ${JSON.stringify(reqStats.byChannel)}`);
  } catch (err) {
    console.log(
      `  [WARN] getReviewRequestStats: ${err instanceof Error ? err.message : err}`
    );
  }

  console.log("");
  console.log("=".repeat(60));
  if (allPassed) {
    console.log("  RESULT: ALL 4 CHECKS PASSED — Wave 1 migration verified");
  } else {
    console.log("  RESULT: SOME CHECKS FAILED — review output above");
  }
  console.log("=".repeat(60));

  process.exit(allPassed ? 0 : 1);
}

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