import { type PrismaService } from '@modules/shared';
import {
  type AgentPublicProfileData,
  type AgentPublicListingItem,
} from '../../domain/repositories/agent.repository';

/** Fetch active listings for an agent's public profile. */
export async function getActiveListingsForAgent(
  prisma: PrismaService,
  agentId: string,
): Promise<AgentPublicListingItem[]> {
  const listings = await prisma.listing.findMany({
    where: { agentId, status: 'ACTIVE' },
    take: 12,
    orderBy: { createdAt: 'desc' },
    select: {
      id: true,
      transactionType: true,
      priceVND: true,
      status: true,
      property: {
        select: {
          id: true,
          title: true,
          propertyType: true,
          address: true,
          district: true,
          city: true,
          areaM2: true,
          bedrooms: true,
          bathrooms: true,
          media: {
            where: { type: 'image' },
            take: 1,
            orderBy: { order: 'asc' },
            select: { url: true },
          },
        },
      },
    },
  });

  return listings.map((l) => ({
    id: l.id,
    transactionType: l.transactionType,
    priceVND: l.priceVND.toString(),
    status: l.status,
    property: {
      id: l.property.id,
      title: l.property.title,
      propertyType: l.property.propertyType,
      address: l.property.address,
      district: l.property.district,
      city: l.property.city,
      areaM2: l.property.areaM2,
      bedrooms: l.property.bedrooms,
      bathrooms: l.property.bathrooms,
      imageUrl: l.property.media[0]?.url ?? null,
    },
  }));
}

/** Build the full public profile data for an agent. */
export async function buildPublicProfile(
  prisma: PrismaService,
  agentId: string,
): Promise<AgentPublicProfileData | null> {
  const agent = await prisma.agent.findUnique({
    where: { id: agentId },
    include: {
      user: {
        select: {
          fullName: true,
          avatarUrl: true,
          phone: true,
          email: true,
          createdAt: true,
        },
      },
    },
  });

  if (!agent) return null;

  const [listings, reviewStats] = await Promise.all([
    getActiveListingsForAgent(prisma, agentId),
    prisma.review.aggregate({
      where: { targetType: 'AGENT', targetId: agentId },
      _avg: { rating: true },
      _count: { rating: true },
    }),
  ]);

  return {
    id: agent.id,
    fullName: agent.user.fullName,
    avatarUrl: agent.user.avatarUrl,
    phone: agent.user.phone,
    email: agent.user.email,
    agency: agent.agency,
    licenseNumber: agent.licenseNumber,
    bio: agent.bio,
    qualityScore: agent.qualityScore,
    totalDeals: agent.totalDeals,
    isVerified: agent.isVerified,
    serviceAreas: (agent.serviceAreas as string[]) ?? [],
    memberSince: agent.createdAt.toISOString(),
    activeListings: listings,
    avgReviewRating: Math.round((reviewStats._avg.rating ?? 0) * 10) / 10,
    totalReviews: reviewStats._count.rating,
  };
}
