/**
 * Staff Dashboard Blog API - Individual Post Operations
 * GET /api/staff/dashboard/blog/[id] - Get single blog post
 * PUT /api/staff/dashboard/blog/[id] - Update blog post
 * DELETE /api/staff/dashboard/blog/[id] - Delete 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 {
  getBlogPostById,
  updateBlogPost,
  deleteBlogPost,
} from "@/lib/services/blog-management.service";
import { validateUpdateBlogPost } from "@/lib/validators/blog-management.validator";
import { sanitizeUpdateBlogPostInput } from "@/lib/sanitizers/blog-management.sanitizer";
import type { UpdateBlogPostInput } 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/[id]
 * Get a single blog post by ID
 */
export async function GET(
  req: NextRequest,
  { params }: { params: { id: string } },
) {
  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");

        // Convex getBlogPostBySlug uses slug — try treating id as slug first,
        // but the [id] route typically receives a DB id. Use slug lookup as
        // Convex doesn't have a getById — the id here may be a Convex _id.
        const post = await convexQuery("content/queries:getBlogPostBySlug", {
          slug: params.id,
        });
        if (post !== null) {
          return NextResponse.json({ post });
        }
        // If slug lookup returns null, the id might be a Prisma UUID —
        // fall through to Prisma.
      } catch {
        // Fall through to Prisma
      }
    }

    const post = await getBlogPostById(params.id);

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

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

/**
 * PUT /api/staff/dashboard/blog/[id]
 * Update an existing blog post
 */
export async function PUT(
  req: NextRequest,
  { params }: { params: { id: string } },
) {
  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();

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

        const convexArgs: Record<string, unknown> = {
          id: params.id, // Convex _id
        };
        if (body.title !== undefined) convexArgs.title = body.title;
        if (body.titleAr !== undefined) convexArgs.titleAr = body.titleAr;
        if (body.slug !== undefined) convexArgs.slug = body.slug;
        if (body.content !== undefined) convexArgs.content = body.content;
        if (body.contentAr !== undefined) convexArgs.contentAr = body.contentAr;
        if (body.excerpt !== undefined) convexArgs.excerpt = body.excerpt;
        if (body.excerptAr !== undefined) convexArgs.excerptAr = body.excerptAr;
        if (body.language !== undefined) convexArgs.language = body.language;
        if (body.authorId !== undefined) convexArgs.authorId = body.authorId;
        if (body.authorName !== undefined)
          convexArgs.authorName = body.authorName;
        if (body.tags !== undefined) convexArgs.tags = body.tags;
        if (body.featured !== undefined) convexArgs.featured = body.featured;
        if (body.metaTitle !== undefined) convexArgs.metaTitle = body.metaTitle;
        if (body.metaDescription !== undefined)
          convexArgs.metaDescription = body.metaDescription;
        if (body.coverImageStorageId !== undefined)
          convexArgs.coverImageStorageId = body.coverImageStorageId;
        if (body.status !== undefined) {
          convexArgs.status =
            statusToConvex[body.status] ?? body.status.toLowerCase();
        }

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

    // Sanitize input
    const sanitizedInput = sanitizeUpdateBlogPostInput(
      body as UpdateBlogPostInput,
    );

    // Validate input
    validateUpdateBlogPost(sanitizedInput);

    // Update blog post
    const post = await updateBlogPost(params.id, sanitizedInput);

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

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

    if (error instanceof Error) {
      if (error.message.includes("not found")) {
        return NextResponse.json({ error: error.message }, { status: 404 });
      }
      return NextResponse.json({ error: error.message }, { status: 400 });
    }

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

/**
 * DELETE /api/staff/dashboard/blog/[id]
 * Delete a blog post and its associated image
 */
export async function DELETE(
  req: NextRequest,
  { params }: { params: { id: string } },
) {
  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 { convexMutation } = await import("@/lib/convex-client");

        const result = await convexMutation(
          "content/mutations:deleteBlogPost",
          {
            id: params.id as any, // Convex _id
          },
        );
        if (result !== null) {
          revalidatePath("/ar/blog");
          revalidatePath("/en/blog");
          return NextResponse.json({ success: true });
        }
      } catch (convexError) {
        if (
          convexError instanceof Error &&
          convexError.message.includes("not found")
        ) {
          return NextResponse.json(
            { error: convexError.message },
            { status: 404 },
          );
        }
        // Fall through to Prisma
      }
    }

    await deleteBlogPost(params.id);

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

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("Error deleting blog post:", error);

    if (error instanceof Error && error.message.includes("not found")) {
      return NextResponse.json({ error: error.message }, { status: 404 });
    }

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