import type { Metadata } from 'next'
import { db } from '@/lib/db'
import { teams } from '@/lib/db/schema'
import { TeamClient } from './client'

type Props = { params: Promise<{ slug: string }> }

function slugify(name: string) {
  return name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params
  const allTeams = await db.select({ name: teams.name }).from(teams)
  const team = allTeams.find(t => slugify(t.name) === slug)
  const name = team?.name ?? slug
  const title = `${name} at the FIFA World Cup`
  const description = `${name} World Cup history — all matches, results, goals and top scorers across every tournament appearance.`
  return {
    title,
    description,
    openGraph: { title, description, url: `/teams/${slug}` },
  }
}

export default function TeamPage({ params }: Props) {
  return <TeamClient params={params} />
}
