import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { processDueReminders } from "@/lib/reminders";

/**
 * Cron endpoint — call every minute to process due reminders.
 *
 * Upgrade #7: Logs every execution to CronLog for monitoring.
 *
 * Setup:
 *   - System cron: * * * * * curl -s -X POST http://localhost:3000/api/cron/send-reminders?key=dev-cron-key
 *   - Vercel Cron: add to vercel.json
 */
export async function POST(req: Request) {
  const url = new URL(req.url);
  const key = url.searchParams.get("key");
  const cronKey = process.env.CRON_SECRET || "dev-cron-key";

  if (process.env.NODE_ENV === "production" && key !== cronKey) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const startTime = Date.now();

  try {
    const results = await processDueReminders();

    // Auto-progression: mark overdue scheduled/confirmed appointments as no_show
    const oneHourAgo = new Date(Date.now() - 60 * 60_000);
    const noShowAppts = await prisma.appointment.findMany({
      where: {
        dateTime: { lt: oneHourAgo },
        status: { in: ["scheduled", "confirmed"] },
        lead: { status: { notIn: ["no_show", "arrived", "completed", "in_progress"] } },
      },
      select: { id: true, leadId: true },
    });
    if (noShowAppts.length > 0) {
      const noShowIds = noShowAppts.map(a => a.id);
      const leadIds = noShowAppts.map(a => a.leadId);
      await prisma.appointment.updateMany({ where: { id: { in: noShowIds } }, data: { status: "no_show" } });
      await prisma.lead.updateMany({ where: { id: { in: leadIds } }, data: { status: "no_show" } });
      console.log(`🚫 Auto-marked ${noShowAppts.length} appointments as no_show`);
    }

    // Auto-progression: mark arrived/in_progress appointments older than 2h as completed
    const twoHoursAgo = new Date(Date.now() - 2 * 60 * 60_000);
    const completedAppts = await prisma.appointment.findMany({
      where: {
        dateTime: { lt: twoHoursAgo },
        status: { in: ["arrived", "in_progress"] },
      },
      select: { id: true, leadId: true },
    });
    if (completedAppts.length > 0) {
      const completedIds = completedAppts.map(a => a.id);
      const completedLeadIds = completedAppts.map(a => a.leadId);
      await prisma.appointment.updateMany({ where: { id: { in: completedIds } }, data: { status: "completed" } });
      await prisma.lead.updateMany({ where: { id: { in: completedLeadIds } }, data: { status: "completed" } });
      console.log(`✅ Auto-marked ${completedAppts.length} appointments as completed`);
    }

    const duration = Date.now() - startTime;

    // Upgrade #7: Log cron execution
    try {
      await prisma.cronLog.create({
        data: {
          type: "send-reminders",
          sent: results.sent,
          skipped: results.skipped,
          failed: results.failed,
          retried: results.retried,
          durationMs: duration,
        },
      });
    } catch (logErr) {
      console.error("⚠️ Failed to log cron execution:", logErr);
    }

    return NextResponse.json({
      success: true,
      ...results,
      durationMs: duration,
      processedAt: new Date().toISOString(),
    });
  } catch (error) {
    const duration = Date.now() - startTime;
    const errMsg = error instanceof Error ? error.message : "Unknown error";

    console.error("❌ Cron fatal error:", error);

    // Log the failure too
    try {
      await prisma.cronLog.create({
        data: {
          type: "send-reminders",
          durationMs: duration,
          error: errMsg,
        },
      });
    } catch { /* don't fail on logging */ }

    return NextResponse.json(
      { error: "Failed to process reminders", message: errMsg },
      { status: 500 }
    );
  }
}

export async function GET(req: Request) {
  return POST(req);
}
