import { notFound } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
import { parseLeagueRules, defaultLeagueRules } from "@/lib/rules/schema";
import { RulesForm } from "./rules-form";

export default async function RulesPage({
  params,
}: {
  params: Promise<{ leagueId: string }>;
}) {
  const { leagueId } = await params;
  const supabase = await createClient();

  const { data: league } = await supabase
    .from("leagues")
    .select("name")
    .eq("id", leagueId)
    .single();

  if (!league) notFound();

  const { data: latest } = await supabase
    .from("league_rules")
    .select("rules, version")
    .eq("league_id", leagueId)
    .order("version", { ascending: false })
    .limit(1)
    .single();

  const rules = latest?.rules
    ? parseLeagueRules(latest.rules)
    : defaultLeagueRules;

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold">League rules</h1>
        <p className="text-sm text-[var(--color-muted)]">
          {league.name} · version {latest?.version ?? 0}
        </p>
      </div>
      <RulesForm leagueId={leagueId} initialRules={rules} />
    </div>
  );
}
