import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";

// GET /api/souq/listings/[id] — single listing with seller info + reviews
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;

    const listing = await prisma.listing.findUnique({
      where: { id },
      include: {
        seller: {
          select: { id: true, name: true, email: true, avatar: true },
        },
        reviews: {
          include: {
            reviewer: {
              select: { id: true, name: true, avatar: true },
            },
          },
          orderBy: { createdAt: "desc" },
        },
        _count: {
          select: { purchases: true },
        },
      },
    });

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

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const data = listing as any;
    return NextResponse.json({
      listing: {
        ...data,
        packages: data.packages ? JSON.parse(data.packages) : null,
        tags: data.tags ? JSON.parse(data.tags) : null,
        images: data.images ? JSON.parse(data.images) : null,
      },
    });
  } catch (error) {
    console.error("GET /api/souq/listings/[id] error:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}
