import { NextRequest, NextResponse } from "next/server";
import { blogService } from "@/lib/blog-service";

export const dynamic = "force-dynamic";

/**
 * GET /api/cron/publish
 * Vercel Cron Job endpoint: Scans for scheduled articles whose publication timestamp
 * has been reached, transitions them to PUBLISHED, and triggers cache revalidation.
 */
export async function GET(req: NextRequest) {
  try {
    // Verify cron authorization header if CRON_SECRET is configured
    const cronSecret = process.env.CRON_SECRET;
    const authHeader = req.headers.get("authorization");

    if (cronSecret && authHeader !== `Bearer ${cronSecret}`) {
      return NextResponse.json({ error: "Unauthorized cron execution" }, { status: 401 });
    }

    const publishedCount = await blogService.processDueScheduledPosts();

    return NextResponse.json({
      success: true,
      publishedCount,
      timestamp: new Date().toISOString(),
    });
  } catch (err: any) {
    console.error("[GET /api/cron/publish] Error:", err);
    return NextResponse.json(
      { error: err.message || "Failed to execute publication cron" },
      { status: 500 }
    );
  }
}

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