/**
 * Staff Dashboard Blog Bulk Operations API
 * POST /api/staff/dashboard/blog/bulk-update - Bulk update blog post status
 */

import { NextRequest, NextResponse } from "next/server";
import { getStaffSession } from "@/lib/staff-session";
import { bulkUpdateStatus } from "@/lib/services/blog-management.service";
import { getDataSource } from "@/lib/data-source";

/** Map Prisma-style UPPERCASE status to Convex lowercase */
const statusToConvex: Record<string, string> = {
  DRAFT: "draft",
  PUBLISHED: "published",
  ARCHIVED: "archived",
};

/**
 * POST /api/staff/dashboard/blog/bulk-update
 * Bulk update blog post status
 */
export async function POST(req: NextRequest) {
  try {
    // Validate staff session
    const session = await getStaffSession();
    if (!session) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const body = await req.json();
    const { ids, status } = body;

    // Validate input
    if (!Array.isArray(ids) || ids.length === 0) {
      return NextResponse.json(
        { error: "Invalid or empty IDs array" },
        { status: 400 },
      );
    }

    if (!["DRAFT", "PUBLISHED", "ARCHIVED"].includes(status)) {
      return NextResponse.json({ error: "Invalid status" }, { status: 400 });
    }

    // --- Convex data-source routing ---
    if (getDataSource("content") === "convex") {
      try {
        const { convexMutation } = await import("@/lib/convex-client");

        const convexStatus = statusToConvex[status] ?? status.toLowerCase();
        const results = await convexMutation(
          "content/mutations:bulkUpdateBlogStatus",
          {
            ids: ids as any[], // Convex _id array
            status: convexStatus as any,
          },
        );
        if (results !== null) {
          const updatedCount = (results as any[]).filter(
            (r: any) => r.success,
          ).length;
          return NextResponse.json({ success: true, updatedCount });
        }
      } catch {
        // Fall through to Prisma
      }
    }

    const updatedCount = await bulkUpdateStatus(ids, status);

    return NextResponse.json({
      success: true,
      updatedCount,
    });
  } catch (error) {
    console.error("Error bulk updating blog posts:", error);
    return NextResponse.json(
      { error: "Failed to bulk update blog posts" },
      { status: 500 },
    );
  }
}
