/**
 * Staff Dashboard Blog API - List and Create
 * GET /api/staff/dashboard/blog - List all blog posts with filters
 * POST /api/staff/dashboard/blog - Create new blog post
 */

export const dynamic = "force-dynamic";

import { NextRequest, NextResponse } from "next/server";
import { revalidatePath } from "next/cache";
import { getStaffSession } from "@/lib/staff-session";
import {
  getBlogPosts,
  createBlogPost,
  getAllBlogTags,
  getAllAuthors,
} from "@/lib/services/blog-management.service";
import {
  validateCreateBlogPost,
  generateSlugFromTitle,
} from "@/lib/validators/blog-management.validator";
import { sanitizeCreateBlogPostInput } from "@/lib/sanitizers/blog-management.sanitizer";
import type {
  BlogPostFilters,
  CreateBlogPostInput,
} from "@/lib/types/blog-management.types";
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",
};

/**
 * GET /api/staff/dashboard/blog
 * List all blog posts with filters and pagination
 */
export async function GET(req: NextRequest) {
  try {
    // Validate staff session
    const session = await getStaffSession();
    if (!session) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { searchParams } = new URL(req.url);

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

        // Special endpoint to get metadata for filters
        if (searchParams.get("meta") === "true") {
          const tags = await convexQuery("content/queries:getAllBlogTags", {});
          // Convex has no separate authors query — return tags only
          return NextResponse.json({ tags: tags ?? [], authors: [] });
        }

        const page = parseInt(searchParams.get("page") || "1", 10);
        const pageSize = parseInt(searchParams.get("pageSize") || "20", 10);
        const offset = (page - 1) * pageSize;

        // Build Convex query args
        const convexArgs: Record<string, unknown> = {
          limit: pageSize,
          offset,
        };
        const rawStatus = searchParams.get("status");
        if (rawStatus) {
          convexArgs.status =
            statusToConvex[rawStatus] ?? rawStatus.toLowerCase();
        }
        if (searchParams.get("lang"))
          convexArgs.language = searchParams.get("lang");
        if (searchParams.get("featured"))
          convexArgs.featured = searchParams.get("featured") === "true";
        if (searchParams.get("author"))
          convexArgs.authorId = searchParams.get("author");
        const tags = searchParams.get("tags");
        if (tags) convexArgs.tag = tags.split(",")[0]; // Convex supports single tag filter

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

    // Parse filters
    const filters: BlogPostFilters = {};
    if (searchParams.get("status"))
      filters.status = searchParams.get("status") as any;
    if (searchParams.get("lang"))
      filters.lang = searchParams.get("lang") as "ar" | "en";
    if (searchParams.get("featured"))
      filters.featured = searchParams.get("featured") === "true";
    if (searchParams.get("author"))
      filters.author = searchParams.get("author")!;
    if (searchParams.get("search"))
      filters.search = searchParams.get("search")!;
    if (searchParams.get("tags")) {
      filters.tags = searchParams.get("tags")!.split(",");
    }
    if (searchParams.get("dateFrom"))
      filters.dateFrom = searchParams.get("dateFrom")!;
    if (searchParams.get("dateTo"))
      filters.dateTo = searchParams.get("dateTo")!;

    // Parse pagination
    const page = parseInt(searchParams.get("page") || "1", 10);
    const pageSize = parseInt(searchParams.get("pageSize") || "20", 10);

    // Special endpoint to get metadata for filters
    if (searchParams.get("meta") === "true") {
      const [tags, authors] = await Promise.all([
        getAllBlogTags(),
        getAllAuthors(),
      ]);

      return NextResponse.json({
        tags,
        authors,
      });
    }

    // Get paginated posts
    const result = await getBlogPosts(filters, page, pageSize);

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

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

    // Parse request body
    const body = await req.json();

    // Auto-generate slug if not provided
    if (!body.slug && body.title) {
      body.slug = generateSlugFromTitle(body.title, body.lang || "en");
    }

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

        const convexStatus =
          statusToConvex[body.status] ?? (body.status || "draft").toLowerCase();
        const convexArgs: Record<string, unknown> = {
          title: body.title,
          slug: body.slug,
          content: body.content || "",
          language: body.lang || body.language || "en",
          authorId: body.authorId || (session as any).id || "staff",
          authorName: body.authorName || (session as any).name || "Staff",
          status: convexStatus,
          tags: body.tags || [],
        };
        if (body.titleAr) convexArgs.titleAr = body.titleAr;
        if (body.contentAr) convexArgs.contentAr = body.contentAr;
        if (body.excerpt) convexArgs.excerpt = body.excerpt;
        if (body.excerptAr) convexArgs.excerptAr = body.excerptAr;
        if (body.featured !== undefined) convexArgs.featured = body.featured;
        if (body.metaTitle) convexArgs.metaTitle = body.metaTitle;
        if (body.metaDescription)
          convexArgs.metaDescription = body.metaDescription;
        if (body.coverImageStorageId)
          convexArgs.coverImageStorageId = body.coverImageStorageId;

        const postId = await convexMutation(
          "content/mutations:createBlogPost",
          convexArgs,
        );
        if (postId !== null) {
          revalidatePath("/ar/blog");
          revalidatePath("/en/blog");
          return NextResponse.json(
            { post: { id: postId, ...convexArgs } },
            { status: 201 },
          );
        }
      } catch (convexError) {
        if (convexError instanceof Error) {
          return NextResponse.json(
            { error: convexError.message },
            { status: 400 },
          );
        }
        // Fall through to Prisma
      }
    }

    // Sanitize input
    const sanitizedInput = sanitizeCreateBlogPostInput(
      body as CreateBlogPostInput,
    );

    // Validate input
    validateCreateBlogPost(sanitizedInput);

    // Create blog post (will generate AI image if requested)
    const post = await createBlogPost(sanitizedInput);

    // Revalidate blog pages
    revalidatePath("/ar/blog");
    revalidatePath("/en/blog");

    return NextResponse.json({ post }, { status: 201 });
  } catch (error) {
    console.error("Error creating blog post:", error);

    if (error instanceof Error) {
      return NextResponse.json({ error: error.message }, { status: 400 });
    }

    return NextResponse.json(
      { error: "Failed to create blog post" },
      { status: 500 },
    );
  }
}
