import { notFound } from "next/navigation";
import { CompetitionDetailClient } from "./client";
import { apiGet } from "@/lib/api/server";

interface Props {
  params: Promise<{ slug: string }>;
}

interface Registration {
  id: string;
  status: string;
  score: number | null;
  rank: number | null;
  user: {
    id: string;
    phone: string;
    profile: { fullName?: string | null; avatar?: string | null } | null;
  };
}

export interface CompetitionDetail {
  id: string;
  title: string;
  slug: string;
  description: string | null;
  sport: { id: string; name: string };
  type: string;
  status: string;
  location: string | null;
  address: string | null;
  startDate: string | null;
  endDate: string | null;
  deadline: string | null;
  capacity: number;
  price: number;
  image: string | null;
  judge: {
    id: string;
    phone: string;
    profile: { fullName?: string | null; avatar?: string | null } | null;
  } | null;
  registrations: Registration[];
  _count: { registrations: number };
}

export default async function CompetitionDetailPage({ params }: Props) {
  const { slug } = await params;

  const all = await apiGet<CompetitionDetail[]>("/api/competitions").catch(() => []);
  const match = all.find((c) => c.slug === slug);
  if (!match) notFound();

  const competition = await apiGet<CompetitionDetail>(`/api/competitions/${match.id}`).catch(() => null);
  if (!competition) notFound();

  return <CompetitionDetailClient competition={competition} />;
}
