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

export const dynamic = "force-dynamic";

/**
 * GET /api/admin/posts
 * Lists posts with server-side pagination, search, status, and category filters.
 */
export async function GET(req: NextRequest) {
  try {
    const ctx = await requireAuth(req);

    const { searchParams } = new URL(req.url);
    const status = (searchParams.get("status") as PostStatus | "ALL") || "ALL";
    const category = searchParams.get("category") || undefined;
    const search = searchParams.get("search") || undefined;
    const limit = Math.min(100, Math.max(1, parseInt(searchParams.get("limit") || "20", 10)));
    const page = Math.max(1, parseInt(searchParams.get("page") || "1", 10));
    const skip = (page - 1) * limit;
    const sortBy = (searchParams.get("sortBy") as any) || "publishedDate";
    const sortOrder = searchParams.get("sortOrder") === "asc" ? 1 : -1;

    // Process any scheduled posts that have reached their target time
    await blogService.processDueScheduledPosts();

    const [posts, total] = await Promise.all([
      db.getPosts({
        status,
        category,
        search,
        limit,
        skip,
        sortBy,
        sortOrder,
        lean: true,
      }),
      db.getPostCount({
        status,
        category,
        search,
      }),
    ]);

    return NextResponse.json({
      posts,
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit) || 1,
      },
    });
  } catch (err: any) {
    console.error("[GET /api/admin/posts] Error:", err);
    return NextResponse.json(
      { error: err.message || "Failed to fetch posts" },
      { status: err.status || 500 }
    );
  }
}

/**
 * POST /api/admin/posts
 * Creates a new article draft in MongoDB.
 */
export async function POST(req: NextRequest) {
  try {
    const ctx = await requirePermission("posts.create", req);
    const body = await req.json();

    const title = typeof body.title === "string" ? body.title.trim() : "";
    if (!title) {
      return NextResponse.json(
        { error: "Article title is required to create a draft." },
        { status: 400 }
      );
    }

    const auditCtx = await getAdminAuditContext(req);

    const post = await blogService.createDraft(
      {
        title,
        category: body.category,
        authorId: body.authorId,
        authorName: body.authorName,
      },
      { ...ctx.user, location: auditCtx.location }
    );

    return NextResponse.json({ post }, { status: 201 });
  } catch (err: any) {
    console.error("[POST /api/admin/posts] Error:", err);
    return NextResponse.json(
      { error: err.message || "Failed to create draft" },
      { status: err.status || 500 }
    );
  }
}
