import { NextRequest, NextResponse } from "next/server";
import { requireAuth, 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]
 * Loads a single post document by its ID.
 */
export async function GET(
  req: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const ctx = await requireAuth(req);

    const { id } = await context.params;
    const post = await db.getPostById(id);

    if (!post) {
      return NextResponse.json({ error: "Article not found" }, { status: 404 });
    }

    const hasWorkingDraft = !!post.workingDraft;
    const editorPost = hasWorkingDraft
      ? {
          ...post,
          ...post.workingDraft,
          author: post.workingDraft?.author || post.author,
          liveSlug: post.slug,
          hasWorkingDraft: true,
        }
      : {
          ...post,
          liveSlug: post.slug,
          hasWorkingDraft: false,
        };

    return NextResponse.json({
      post: editorPost,
      hasWorkingDraft,
      liveSlug: post.slug,
      isPublished: post.status === "PUBLISHED",
    });
  } catch (err: any) {
    console.error("[GET /api/admin/posts/[id]] Error:", err);
    return NextResponse.json(
      { error: err.message || "Failed to fetch post" },
      { status: err.status || 500 }
    );
  }
}

/**
 * PATCH /api/admin/posts/[id]
 * Autosaves or updates post draft content, SEO fields, images, or metadata.
 */
export async function PATCH(
  req: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const ctx = await requirePermission("posts.edit", req);
    const { id } = await context.params;
    const body = await req.json();
    const auditCtx = await getAdminAuditContext(req);

    const updated = await blogService.updateDraft(id, body, {
      ...ctx.user,
      location: auditCtx.location,
    });
    return NextResponse.json({ post: updated });
  } catch (err: any) {
    console.error("[PATCH /api/admin/posts/[id]] Error:", err);
    return NextResponse.json(
      { error: err.message || "Failed to update article" },
      { status: err.status || 500 }
    );
  }
}

/**
 * DELETE /api/admin/posts/[id]
 * Deletes a draft article.
 * ENFORCES DELETE SAFETY: Rejects requests targeting PUBLISHED articles.
 */
export async function DELETE(
  req: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const ctx = await requirePermission("posts.edit", req);
    const { id } = await context.params;

    const existing = await db.getPostById(id);
    if (!existing) {
      return NextResponse.json({ error: "Article not found" }, { status: 404 });
    }

    if (existing.status === "PUBLISHED") {
      return NextResponse.json(
        {
          error:
            "Cannot delete a published article. To remove it from public view, archive it instead.",
        },
        { status: 400 }
      );
    }

    const auditCtx = await getAdminAuditContext(req);
    const deleted = await db.deletePost(id);

    await db.logContentEvent({
      actorId: ctx.user.id,
      actorName: ctx.user.name,
      actorEmail: ctx.user.email,
      actorRole: ctx.user.role,
      location: auditCtx.location || null,
      postId: existing.id,
      postTitle: existing.title,
      postSlug: existing.slug,
      action: "POST_DELETED",
      details: { previousStatus: existing.status },
    });

    return NextResponse.json({ success: deleted });
  } catch (err: any) {
    console.error("[DELETE /api/admin/posts/[id]] Error:", err);
    return NextResponse.json(
      { error: err.message || "Failed to delete article" },
      { status: err.status || 500 }
    );
  }
}
