import prisma from "@/lib/prisma";
import EscortCard from "@/components/shared/escort-card";
import { withAvatarUrls } from "@/lib/media";

interface SimilarEscortsProps {
  userId: number;
  cityId: number | null;
  countryId: number | null;
}

export default async function SimilarEscorts({ userId, cityId, countryId }: SimilarEscortsProps) {
  if (!cityId && !countryId) return null;

  // Pull a country-wide pool in one query and partition client-side: same-
  // city escorts first, then country fallback. Earlier code did 2 sequential
  // round-trips and pulled full country/city rows (with large SEO @db.Text
  // columns) — here we slim the include + halve the trips.
  const slimSelect = {
    name: true,
    slug: true,
  };
  // R15 C.9: explicit select — `include` previously pulled every column on
  // the users table including bio/SEO text fields not used by the card.
  const pool = await prisma.user.findMany({
    where: {
      user_type: "escort",
      active: true,
      banned_at: null,
      id: { not: userId },
      OR: [
        ...(cityId ? [{ city_id: cityId }] : []),
        ...(countryId ? [{ country_id: countryId }] : []),
      ],
    },
    select: {
      id: true,
      id_aw: true,
      username: true,
      profile_photo: true,
      is_verified: true,
      is_vip: true,
      status: true,
      lastonline_at: true,
      city_id: true,
      country: { select: slimSelect },
      city: { select: slimSelect },
    },
    orderBy: { hits: "desc" },
    take: 12,
  });

  const inCity = cityId ? pool.filter((p) => p.city_id === cityId) : [];
  const rest = pool.filter((p) => !cityId || p.city_id !== cityId);
  const escorts = (await withAvatarUrls([...inCity, ...rest])).slice(0, 6);

  if (escorts.length === 0) return null;

  return (
    <div className="bg-surface rounded-lg p-6">
      <h2 className="text-lg font-semibold mb-4">You May Also Like</h2>
      <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4">
        {escorts.map((escort) => (
          <EscortCard key={escort.id} escort={escort} />
        ))}
      </div>
    </div>
  );
}
