/**
 * Staff Dashboard Blog Stats API
 * GET /api/staff/dashboard/blog/stats - Get blog statistics
 */

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

/**
 * GET /api/staff/dashboard/blog/stats
 * Get blog statistics for dashboard overview
 */
export async function GET(req: NextRequest) {
  try {
    // Validate staff session
    const session = await getStaffSession();
    if (!session) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

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

        const stats = await convexQuery("content/queries:getBlogStats", {});
        if (stats !== null) {
          return NextResponse.json({ stats });
        }
      } catch {
        // Fall through to Prisma
      }
    }

    const stats = await getBlogStats();

    return NextResponse.json({ stats });
  } catch (error) {
    console.error("Error fetching blog stats:", error);
    return NextResponse.json(
      { error: "Failed to fetch blog statistics" },
      { status: 500 },
    );
  }
}
