import prisma from "@/lib/prisma";
import Link from "next/link";
import RecommendedEscortsClient from "./recommended-escorts-client";
import { withAvatarUrls } from "@/lib/media";

interface RecommendedEscortsProps {
  userId: number;
}

export interface RecommendedEscort {
  id: number;
  id_aw: string | null;
  username: string | null;
  profile_photo: string | null;
  avatarMediaUrls: string[];
  city: { name: string } | null;
  reason: string;
}

export default async function RecommendedEscorts({ userId }: RecommendedEscortsProps) {
  try {
  // Find user's recent favorited escorts
  const recentFavorites = await prisma.favorite.findMany({
    where: {
      user_id: userId,
      markable_type: "App\\Models\\User",
    },
    orderBy: { created_at: "desc" },
    take: 10,
  });

  const favoritedIds = recentFavorites.map((f) => f.markable_id);
  const hasFavorites = favoritedIds.length > 0;

  let recommended: RecommendedEscort[] = [];

  if (favoritedIds.length > 0) {
    // Get characteristics of favorited escorts for similarity matching
    const favCharacteristics = await prisma.characteristic.findMany({
      where: { user_id: { in: favoritedIds } },
      select: { ethnicity_id: true, age_id: true },
    });

    const ethnicityIds = [
      ...new Set(favCharacteristics.map((c) => c.ethnicity_id).filter(Boolean)),
    ] as number[];
    const ageIds = [
      ...new Set(favCharacteristics.map((c) => c.age_id).filter(Boolean)),
    ] as number[];

    const excludeIds = [userId, ...favoritedIds];

    if (ethnicityIds.length > 0 || ageIds.length > 0) {
      // Find similar escorts based on ethnicity or age range
      const similarCharacteristics = await prisma.characteristic.findMany({
        where: {
          user_id: { notIn: excludeIds },
          OR: [
            ...(ethnicityIds.length > 0
              ? [{ ethnicity_id: { in: ethnicityIds } }]
              : []),
            ...(ageIds.length > 0 ? [{ age_id: { in: ageIds } }] : []),
          ],
        },
        select: { user_id: true },
        take: 20,
      });

      const candidateIds = similarCharacteristics.map((c) => c.user_id);

      if (candidateIds.length > 0) {
        const users = await prisma.user.findMany({
          where: {
            id: { in: candidateIds },
            user_type: "escort",
            active: true,
            banned_at: null,
          },
          select: {
            id: true,
            id_aw: true,
            username: true,
            profile_photo: true,
            city: { select: { name: true } },
          },
          take: 8,
        });
        recommended = (await withAvatarUrls(users)).map((u) => ({
          ...u,
          reason: "Similar to escorts you've favorited",
        }));
      }
    }
  }

  // Fallback: top verified escorts
  if (recommended.length === 0) {
    const users = await prisma.user.findMany({
      where: {
        user_type: "escort",
        active: true,
        banned_at: null,
        is_verified: true,
        id: { not: userId },
      },
      orderBy: { hits: "desc" },
      select: {
        id: true,
        id_aw: true,
        username: true,
        profile_photo: true,
        city: { select: { name: true } },
      },
      take: 8,
    });
    recommended = (await withAvatarUrls(users)).map((u) => ({
      ...u,
      reason: hasFavorites ? "Popular in your area" : "Top verified escort",
    }));
  }

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

  return <RecommendedEscortsClient initialEscorts={recommended} userId={userId} />;
  } catch (error) {
    console.error("RecommendedEscorts error:", error);
    return null;
  }
}
