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

/**
 * Upgrade #7: Cron status monitoring endpoint
 *
 * Returns:
 * - Last cron run time + result
 * - Health check status
 * - Pending/failed reminder counts
 * - Alerts if cron hasn't run recently
 */
export async function GET() {
  const session = await getSession();
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const now = new Date();
  const fiveMinAgo = new Date(now.getTime() - 5 * 60_000);
  const fifteenMinAgo = new Date(now.getTime() - 15 * 60_000);
  const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60_000);

  // Last cron runs
  const [lastReminderCron, lastHealthCheck] = await Promise.all([
    prisma.cronLog.findFirst({
      where: { type: "send-reminders" },
      orderBy: { ranAt: "desc" },
    }),
    prisma.cronLog.findFirst({
      where: { type: "health-check" },
      orderBy: { ranAt: "desc" },
    }),
  ]);

  // Pending/failed reminder counts
  const [pendingCount, failedRetryable, failedPermanent] = await Promise.all([
    prisma.scheduledReminder.count({
      where: { status: "pending", appointment: { clinicId: session.id } },
    }),
    prisma.scheduledReminder.count({
      where: {
        status: "failed",
        retryCount: { lt: 3 },
        nextRetryAt: { not: null },
        appointment: { clinicId: session.id },
      },
    }),
    prisma.scheduledReminder.count({
      where: {
        status: "failed",
        retryCount: { gte: 3 },
        appointment: { clinicId: session.id },
      },
    }),
  ]);

  // Last 24h cron stats
  const recentCrons = await prisma.cronLog.findMany({
    where: { type: "send-reminders", ranAt: { gte: oneDayAgo } },
    orderBy: { ranAt: "desc" },
  });

  const last24h = {
    runs: recentCrons.length,
    totalSent: recentCrons.reduce((s, c) => s + c.sent, 0),
    totalSkipped: recentCrons.reduce((s, c) => s + c.skipped, 0),
    totalFailed: recentCrons.reduce((s, c) => s + c.failed, 0),
    totalRetried: recentCrons.reduce((s, c) => s + c.retried, 0),
    errors: recentCrons.filter(c => c.error).length,
    avgDurationMs: recentCrons.length > 0
      ? Math.round(recentCrons.reduce((s, c) => s + c.durationMs, 0) / recentCrons.length)
      : 0,
  };

  // Build alerts
  const alerts: { level: "info" | "warning" | "critical"; message: string }[] = [];

  if (!lastReminderCron) {
    alerts.push({ level: "critical", message: "Reminder cron has never run. Set up: curl -X POST http://localhost:3000/api/cron/send-reminders?key=dev-cron-key" });
  } else if (lastReminderCron.ranAt < fifteenMinAgo) {
    alerts.push({ level: "critical", message: `Reminder cron hasn't run in ${Math.round((now.getTime() - lastReminderCron.ranAt.getTime()) / 60_000)} minutes!` });
  } else if (lastReminderCron.ranAt < fiveMinAgo) {
    alerts.push({ level: "warning", message: `Reminder cron last ran ${Math.round((now.getTime() - lastReminderCron.ranAt.getTime()) / 60_000)} minutes ago` });
  }

  if (!lastHealthCheck) {
    alerts.push({ level: "warning", message: "Health check cron has never run" });
  } else if (lastHealthCheck.ranAt < new Date(now.getTime() - 30 * 60_000)) {
    alerts.push({ level: "warning", message: "Health check hasn't run in 30+ minutes" });
  }

  if (failedPermanent > 0) {
    alerts.push({ level: "warning", message: `${failedPermanent} reminders permanently failed (after 3 retries)` });
  }

  if (failedRetryable > 0) {
    alerts.push({ level: "info", message: `${failedRetryable} reminders queued for retry` });
  }

  // WhatsApp status
  const clinic = await prisma.clinic.findUnique({
    where: { id: session.id },
    select: { wahaStatus: true, wahaLastChecked: true },
  });

  if (clinic?.wahaStatus !== "connected") {
    alerts.push({
      level: "critical",
      message: `WhatsApp is ${clinic?.wahaStatus || "disconnected"}. Reminders cannot be sent.`,
    });
  }

  return NextResponse.json({
    reminderCron: lastReminderCron ? {
      lastRun: lastReminderCron.ranAt,
      sent: lastReminderCron.sent,
      skipped: lastReminderCron.skipped,
      failed: lastReminderCron.failed,
      retried: lastReminderCron.retried,
      durationMs: lastReminderCron.durationMs,
      error: lastReminderCron.error,
    } : null,
    healthCheck: lastHealthCheck ? {
      lastRun: lastHealthCheck.ranAt,
      error: lastHealthCheck.error,
    } : null,
    whatsapp: {
      status: clinic?.wahaStatus || "disconnected",
      lastChecked: clinic?.wahaLastChecked,
    },
    queue: {
      pending: pendingCount,
      retrying: failedRetryable,
      permanentlyFailed: failedPermanent,
    },
    last24h,
    alerts,
  });
}
