import { notFound } from 'next/navigation';
import { LeaguesPageClient } from './LeaguesPageClient';
import { LeaguesPageQuery } from '@/lib/page-queries/LeaguesPageQuery';
import { Metadata } from 'next';
import { MetadataHelper } from '@/lib/seo/MetadataHelper';

export const metadata: Metadata = MetadataHelper.generate({
  title: 'iRacing Leagues',
  description: 'Find and join the most professional iRacing leagues on GridPilot. Automated results, professional race control, and obsessive attention to detail for every series.',
  path: '/leagues',
});

export default async function Page() {
  // Execute the PageQuery
  const result = await LeaguesPageQuery.execute();
  
  // Handle different result types
  if (result.isErr()) {
    const error = result.getError();
    
    switch (error) {
      case 'notFound':
        notFound();
      case 'redirect':
        // In a real app, this would redirect to login
        notFound();
      case 'LEAGUES_FETCH_FAILED':
      case 'UNKNOWN_ERROR':
      default:
        // Return error state - use LeaguesTemplate with empty data
        return <LeaguesPageClient viewData={{ leagues: [] }} />;
    }
  }
  
  const viewData = result.unwrap();

  return <LeaguesPageClient viewData={viewData} />;
}