/**
 * Appointment Reminders Cron Endpoint
 *
 * Scheduled job that runs once a day in the morning to send 24-hour
 * WhatsApp reminders for every upcoming booking across all organizations.
 *
 * Triggered externally by the host scheduler:
 * - cPanel / WHM Cron Jobs (production)
 * - Any hourly/daily scheduler that can curl an HTTPS endpoint
 *
 * Suggested cPanel cron schedule (9:00 AM Doha / 06:00 UTC, daily):
 *   0 6 * * * curl -s -H "Authorization: Bearer $CRON_SECRET" \
 *     https://app.mawidi.com/api/cron/appointment-reminders
 *
 * Security:
 * - Requires CRON_SECRET env var to be set.
 * - Must be called with `Authorization: Bearer <CRON_SECRET>` header.
 *
 * Idempotency:
 * - Safe to run multiple times per day; the underlying service skips any
 *   booking whose `reminderSentAt` is already set.
 */

import { NextResponse } from "next/server";
import { appointmentReminderService } from "@/lib/services/appointment-reminder.service";

function isAuthorized(request: Request): boolean {
  const authHeader = request.headers.get("authorization");
  if (!authHeader) return false;
  const cronSecret = process.env.CRON_SECRET;
  if (!cronSecret) return false;
  return authHeader === `Bearer ${cronSecret}`;
}

export async function GET(request: Request) {
  if (!isAuthorized(request)) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const startTime = Date.now();
  try {
    const result = await appointmentReminderService.processAppointmentReminders();
    return NextResponse.json({
      ok: true,
      durationMs: Date.now() - startTime,
      processedCount: result.processedCount,
      sentCount: result.sentCount,
      failedCount: result.failedCount,
      skippedCount: result.skippedCount,
    });
  } catch (error) {
    return NextResponse.json(
      {
        ok: false,
        error: String(error instanceof Error ? error.message : error),
        durationMs: Date.now() - startTime,
      },
      { status: 500 },
    );
  }
}
