import { db } from '@/lib/prisma';

type GeoStatsCountry = {
  country: string;
  countryCode: string;
  totalUsers: number;
  cities: { city: string; userCount: number }[];
};

export async function getGeoStats(): Promise<{
  countries: GeoStatsCountry[];
  totalUniqueCountries: number;
}> {
  const sessions = await db.session.findMany({
    where: {
      country: { not: null },
      expiresAt: { gt: new Date() },
    },
    select: {
      country: true,
      countryCode: true,
      city: true,
      userId: true,
    },
  });

  const countryMap = new Map<
    string,
    { country: string; countryCode: string; users: Set<string>; cities: Map<string, Set<string>> }
  >();

  for (const s of sessions) {
    const code = s.countryCode || 'XX';
    let entry = countryMap.get(code);
    if (!entry) {
      entry = {
        country: s.country || 'Desconocido',
        countryCode: code,
        users: new Set(),
        cities: new Map(),
      };
      countryMap.set(code, entry);
    }
    entry.users.add(s.userId);

    const cityName = s.city || 'Desconocida';
    let cityUsers = entry.cities.get(cityName);
    if (!cityUsers) {
      cityUsers = new Set();
      entry.cities.set(cityName, cityUsers);
    }
    cityUsers.add(s.userId);
  }

  const countries = Array.from(countryMap.values())
    .map((entry) => ({
      country: entry.country,
      countryCode: entry.countryCode,
      totalUsers: entry.users.size,
      cities: Array.from(entry.cities.entries())
        .map(([city, users]) => ({ city, userCount: users.size }))
        .sort((a, b) => b.userCount - a.userCount),
    }))
    .sort((a, b) => b.totalUsers - a.totalUsers);

  return { countries, totalUniqueCountries: countries.length };
}
