import { NextRequest, NextResponse } from "next/server";
import { requirePermission, getAdminAuditContext } from "@/lib/admin/auth";
import { blogService } from "@/lib/blog-service";
import { db } from "@/lib/admin/db";

export const dynamic = "force-dynamic";

/**
 * GET /api/admin/posts/[id]/revisions
 * Lists all historical snapshots for an article, sorted latest first.
 */
export async function GET(
  req: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  try {
    await requirePermission("posts.edit", req);
    const { id } = await context.params;

    const revisions = await db.getRevisions(id);
    return NextResponse.json({ revisions });
  } catch (err: any) {
    console.error("[GET /api/admin/posts/[id]/revisions] Error:", err);
    return NextResponse.json(
      { error: err.message || "Failed to fetch revisions" },
      { status: err.status || 500 }
    );
  }
}

/**
 * POST /api/admin/posts/[id]/revisions
 * Restores a selected historical snapshot by creating a NEW revision (never erases history).
 */
export async function POST(
  req: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const ctx = await requirePermission("posts.edit", req);
    const body = await req.json();
    const revisionId = body.revisionId;

    if (!revisionId) {
      return NextResponse.json(
        { error: "Revision ID is required to restore." },
        { status: 400 }
      );
    }

    const auditCtx = await getAdminAuditContext(req);
    const restoredPost = await blogService.restoreRevision(revisionId, {
      ...ctx.user,
      location: auditCtx.location,
    });
    return NextResponse.json({ post: restoredPost });
  } catch (err: any) {
    console.error("[POST /api/admin/posts/[id]/revisions] Error:", err);
    return NextResponse.json(
      { error: err.message || "Failed to restore revision" },
      { status: err.status || 500 }
    );
  }
}
