/**
 * Demo Reminders Cron Endpoint
 *
 * Scheduled job that runs hourly to send 24-hour reminders for upcoming demo bookings.
 *
 * Security:
 * - Requires CRON_SECRET authorization header (for Vercel Cron)
 * - Also accepts N8N_WEBHOOK_AUTH_TOKEN (for n8n triggering)
 *
 * Usage:
 * - Vercel Cron: Automatically called based on vercel.json cron config
 * - Manual: GET /api/cron/demo-reminders with Authorization header
 * - n8n: Can be triggered via n8n workflow
 */

import { NextResponse } from "next/server";
import {
  processReminders,
  ProcessRemindersResult,
} from "@/lib/services/demo-reminder.service";
import { systemSettingsService } from "@/lib/services/system-settings.service";
import { getDataSource } from "@/lib/data-source";

// Verify authorization
async function isAuthorized(request: Request): Promise<boolean> {
  const authHeader = request.headers.get("authorization");

  if (!authHeader) {
    return false;
  }

  // Check for Vercel Cron secret
  const cronSecret = process.env.CRON_SECRET;
  if (cronSecret && authHeader === `Bearer ${cronSecret}`) {
    return true;
  }

  // Check for n8n webhook token (from database or env fallback)
  const providedToken = authHeader.replace("Bearer ", "");
  const isValidN8NToken =
    await systemSettingsService.validateN8NToken(providedToken);
  if (isValidN8NToken) {
    return true;
  }

  return false;
}

export async function GET(request: Request) {
  // Verify authorization
  if (!(await isAuthorized(request))) {
    console.warn("Unauthorized cron request attempt");
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  console.log("Starting demo reminder cron job...");
  const startTime = Date.now();

  try {
    // Convex data-source routing (WU-18)
    // When bookings domain is on Convex, the demo-reminder service
    // needs to read demo_bookings from Convex instead of Prisma.
    // For now, the service layer still uses Prisma internally.
    // Full Convex routing requires updating demo-reminder.service.ts.
    if (getDataSource("bookings") === "convex") {
      try {
        const { convexQuery } = await import("@/lib/convex-client");
        // Fetch upcoming demo bookings that need reminders
        const now = Date.now();
        const twentyFourHoursLater = now + 24 * 60 * 60 * 1000;
        const demoBookings = await convexQuery(
          "bookings/queries:getDemoBookings",
          {
            status: "confirmed",
            startDate: now,
            endDate: twentyFourHoursLater,
            limit: 100,
          },
        );
        if (demoBookings !== null) {
          console.log(
            `[Convex] Found ${(demoBookings as unknown[]).length} demo bookings for reminders`,
          );
          // Note: email sending still uses the existing service; only DB reads are routed
        }
      } catch {
        // Fall through to Prisma-backed service
      }
    }

    const result: ProcessRemindersResult = await processReminders();

    const duration = Date.now() - startTime;

    console.log(`Demo reminder cron completed in ${duration}ms:`, {
      processed: result.processed,
      sent: result.sent,
      failed: result.failed,
      skipped: result.skipped,
    });

    return NextResponse.json({
      success: true,
      duration: `${duration}ms`,
      ...result,
    });
  } catch (error) {
    const errorMessage =
      error instanceof Error ? error.message : "Unknown error";
    console.error("Demo reminder cron failed:", error);

    return NextResponse.json(
      {
        success: false,
        error: errorMessage,
        duration: `${Date.now() - startTime}ms`,
      },
      { status: 500 },
    );
  }
}

// Also support POST for n8n webhook compatibility
export async function POST(request: Request) {
  return GET(request);
}

// Configure for Vercel Edge (optional, for faster cold starts)
// export const runtime = 'edge';

// Disable body parsing for cron (GET requests don't have body)
export const dynamic = "force-dynamic";
