import { redirect } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
import { applyTierOverrides, TIER_OVERRIDES } from "@/lib/melon/constants";
import { CorneView } from "./corne-view";

export type MelonScoreEntry = {
  id: string;
  pseudo: string;
  avatar_url: string | null;
  best_score: number;
};

export type MemberRow = {
  id: string;
  pseudo: string;
  avatar_url: string | null;
};

export default async function CornePage() {
  const supabase = await createClient();
  const {
    data: { user },
  } = await supabase.auth.getUser();

  if (!user) {
    redirect("/login");
  }

  const [{ data: scores }, { data: members }, { data: settings }] = await Promise.all([
    supabase
      .from("melon_scores")
      .select("user_id, best_score")
      .order("best_score", { ascending: false }),
    supabase.from("profiles").select("id, pseudo, avatar_url, role").order("pseudo", { ascending: true }),
    supabase.from("settings").select("tribunal_date").eq("id", true).single(),
  ]);

  const memberById = new Map((members ?? []).map((member) => [member.id, member]));

  const leaderboard: MelonScoreEntry[] = (scores ?? []).map((row) => ({
    id: row.user_id,
    pseudo: memberById.get(row.user_id)?.pseudo ?? "Un Citoyen",
    avatar_url: memberById.get(row.user_id)?.avatar_url ?? null,
    best_score: row.best_score,
  }));

  // Un palier de taille par Citoyen (pas les Archontes) : chacun est
  // associé à une taille fixe pour toute la partie, voir corne-view.tsx.
  // applyTierOverrides place d'abord les Citoyens fixés à la main
  // (TIER_OVERRIDES), puis remplit le reste dans l'ordre alphabétique.
  const orderedCitizens: MemberRow[] = (members ?? [])
    .filter((member) => member.role === "public")
    .map(({ id, pseudo, avatar_url }) => ({ id, pseudo, avatar_url }));
  const citizens = applyTierOverrides(orderedCitizens, TIER_OVERRIDES);

  const isFrozen = Boolean(settings?.tribunal_date && new Date() >= new Date(settings.tribunal_date));
  const ownBestScore = leaderboard.find((entry) => entry.id === user.id)?.best_score ?? null;

  return (
    <CorneView
      citizens={citizens}
      initialLeaderboard={leaderboard}
      initialOwnBestScore={ownBestScore}
      isFrozen={isFrozen}
    />
  );
}
