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

// GET /api/souq/sellers/[id] — seller profile data
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;

    // Get user info
    const user = await prisma.user.findUnique({
      where: { id },
      select: {
        id: true,
        name: true,
        email: true,
        avatar: true,
        createdAt: true,
      },
    });

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

    // Get review stats
    const reviewAgg = await prisma.review.aggregate({
      where: { sellerId: id },
      _avg: { rating: true },
      _count: true,
    });

    // Get sales count
    const salesCount = await prisma.purchase.count({
      where: { sellerId: id },
    });

    // Get active listings
    const listings = await prisma.listing.findMany({
      where: { sellerId: id, status: "active" },
      orderBy: { createdAt: "desc" },
      include: {
        seller: {
          select: { id: true, name: true, email: true, avatar: true },
        },
      },
    });

    // Parse JSON fields
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const parsedListings = listings.map((l: any) => ({
      ...l,
      packages: l.packages ? JSON.parse(l.packages) : null,
      tags: l.tags ? JSON.parse(l.tags) : null,
      images: l.images ? JSON.parse(l.images) : null,
    }));

    return NextResponse.json({
      seller: {
        id: user.id,
        name: user.name,
        email: user.email,
        avatar: user.avatar,
        memberSince: user.createdAt,
        listingsCount: parsedListings.length,
        averageRating: reviewAgg._avg.rating ?? 0,
        reviewCount: reviewAgg._count,
        salesCount,
        listings: parsedListings,
      },
    });
  } catch (error) {
    console.error("GET /api/souq/sellers/[id] error:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}
