import { prisma } from "../src/prisma.js";

/**
 * Backfill: make historical GRM rows agree with the current rules.
 *
 * It only ever *fills in missing values* — it never overwrites a value that is
 * already set:
 *
 * 1. Threads that already have a provider/M&E reply but no `firstTpResponseAt`
 *    get it stamped from the first reply (so timeliness is judged on the response
 *    date). This is the only "interesting" change.
 * 2. Any thread that has been responded to is marked `status = resolved` and gets
 *    a `resolvedAt` (only if it is still null). Status is no longer set by hand —
 *    the old "resolved" dropdown was removed.
 * 3. Threads still with no reply keep `status = open`.
 *
 * SAFETY: the script is a **dry run by default**. Nothing is written unless you
 * pass `--apply`.
 *
 *   npm run db:backfill-feedback-response-timestamps              # preview only
 *   npx tsx --import dotenv/config scripts/backfill-feedback-response-timestamps.ts --apply
 */

const APPLY = process.argv.includes("--apply");

type Change = {
  refCode: string;
  action: string;
  before: string;
  after: string;
};

async function backfillFeedbackResponseTimestamps() {
  console.log(APPLY ? "Backfill (APPLY mode — writes to the database)" : "Backfill (DRY RUN — no writes)");
  console.log("=".repeat(72));

  const threads = await prisma.feedbackThread.findMany({
    include: {
      messages: {
        where: { authorType: { not: "public" } },
        orderBy: { createdAt: "asc" },
        take: 1,
        select: { createdAt: true },
      },
    },
    orderBy: { id: "asc" },
  });

  console.log(`Checked ${threads.length} feedback thread(s)\n`);

  const changes: Change[] = [];

  for (const thread of threads) {
    const firstStaffMessage = thread.messages[0];
    const hasResponse = Boolean(thread.firstTpResponseAt) || Boolean(firstStaffMessage);
    const data: Record<string, unknown> = {};

    if (!hasResponse) {
      // No reply at all -> the case is still open, whatever the stored status says.
      if (thread.status !== "open") {
        data.status = "open";
        data.resolvedAt = null;
        changes.push({
          refCode: thread.refCode,
          action: "status",
          before: `${thread.status} / resolvedAt=${thread.resolvedAt?.toISOString() ?? "null"}`,
          after: "open / resolvedAt=null",
        });
      }
    } else {
      const firstResponseAt = thread.firstTpResponseAt ?? firstStaffMessage!.createdAt;

      // Guard: a response timestamp can never predate the submission itself.
      const safeResponseAt = firstResponseAt >= thread.submittedAt ? firstResponseAt : thread.submittedAt;

      if (!thread.firstTpResponseAt) {
        data.firstTpResponseAt = safeResponseAt;
        changes.push({
          refCode: thread.refCode,
          action: "firstTpResponseAt",
          before: "null",
          after: `${safeResponseAt.toISOString()} (timely=${safeResponseAt <= thread.dueAt ? "YES" : "NO"})`,
        });
      }
      if (thread.status !== "resolved") {
        data.status = "resolved";
        changes.push({ refCode: thread.refCode, action: "status", before: thread.status, after: "resolved" });
      }
      if (!thread.resolvedAt) {
        data.resolvedAt = safeResponseAt;
        changes.push({
          refCode: thread.refCode,
          action: "resolvedAt",
          before: "null",
          after: safeResponseAt.toISOString(),
        });
      }
    }

    if (APPLY && Object.keys(data).length > 0) {
      await prisma.feedbackThread.update({ where: { id: thread.id }, data });
    }
  }

  if (changes.length === 0) {
    console.log("Nothing to do — every thread is already consistent with the current rules.");
  } else {
    console.log(`Planned changes: ${changes.length} field update(s) across the rows below\n`);
    for (const c of changes) {
      console.log(`  ${c.refCode}  ${c.action.padEnd(20)} ${c.before}  ->  ${c.after}`);
    }
    if (!APPLY) {
      console.log("\nDRY RUN: nothing was written. Re-run with --apply to commit these changes.");
    }
  }

  // Post-run (or current-state) statistics, always computed from what is actually stored.
  const total = await prisma.feedbackThread.count();
  const responded = await prisma.feedbackThread.count({ where: { firstTpResponseAt: { not: null } } });
  const timely = await prisma.feedbackThread.count({
    where: {
      firstTpResponseAt: { not: null },
      firstTpResponseAt: { lte: prisma.feedbackThread.fields.dueAt },
    },
  });
  const overdueUnresponded = await prisma.feedbackThread.count({
    where: { firstTpResponseAt: null, dueAt: { lt: new Date() } },
  });
  const denominator = responded + overdueUnresponded;

  console.log("\nCurrent stored state:");
  console.log(`  Total feedback threads:        ${total}`);
  console.log(`  Threads with a response:       ${responded}`);
  console.log(`  Timely responses:              ${timely}`);
  console.log(`  Late responses:                ${responded - timely}`);
  console.log(`  Overdue without response:      ${overdueUnresponded}`);
  console.log(`  Timely rate:                   ${denominator > 0 ? Math.round((timely / denominator) * 1000) / 10 : 0}%`);
}

backfillFeedbackResponseTimestamps()
  .then(() => {
    process.exit(0);
  })
  .catch((error) => {
    console.error("\n✗ Backfill failed:", error);
    process.exit(1);
  });
