import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth";

// POST /api/reminders/retry-failed
// Resets ALL permanently failed reminders (retryCount >= 3) back to pending
// Only for the authenticated clinic
export async function POST() {
  const session = await getSession();
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const clinicId = session.id;

  const failed = await prisma.scheduledReminder.findMany({
    where: {
      status: "failed",
      retryCount: { gte: 3 },
      appointment: { clinicId },
    },
    select: { id: true },
  });

  if (failed.length === 0) {
    return NextResponse.json({ reset: 0, message: "No failed reminders to retry" });
  }

  const ids = failed.map((r) => r.id);

  await prisma.scheduledReminder.updateMany({
    where: { id: { in: ids } },
    data: {
      status: "pending",
      retryCount: 0,
      nextRetryAt: null,
      failureReason: null,
    },
  });

  return NextResponse.json({
    reset: ids.length,
    message: `${ids.length} reminder${ids.length !== 1 ? "s" : ""} queued for retry`,
  });
}
