import { adminClient } from "@/sanity/client";

export async function POST(request: Request) {
  try {
    const { docId } = await request.json();

    if (!docId) {
      return new Response("Missing post ID", { status: 400 });
    }

    // Perform an atomic transaction to increment the views
    const result = await adminClient
      .patch(docId) // Assuming this is your document ID format
      .setIfMissing({ viewsCount: 0 })
      .inc({ viewsCount: 1 })
      .commit();

    return Response.json({ success: true, views: result.views });
  } catch (error) {
    console.error("Error updating view count:", error);
    return new Response("Error updating view count", { status: 500 });
  }
}
