import { redirect } from 'next/navigation';
import { routes } from '@/lib/routing/RouteConfig';
import { DriversPageQuery } from '@/lib/page-queries/DriversPageQuery';
import { DriversPageClient } from '@/client-wrapper/DriversPageClient';
import { Metadata } from 'next';
import { MetadataHelper } from '@/lib/seo/MetadataHelper';

export const metadata: Metadata = MetadataHelper.generate({
  title: 'Sim Racing Drivers',
  description: 'Explore the elite roster of sim racing drivers on GridPilot. Detailed performance metrics, career history, and professional driver profiles for the iRacing community.',
  path: '/drivers',
});

export default async function Page({ searchParams }: { searchParams: Promise<{ empty?: string }> }) {
  const { empty } = await searchParams;
  
  if (empty === 'true') {
    return (
      <DriversPageClient
        viewData={{
          drivers: [],
          totalRaces: 0,
          totalRacesLabel: '0',
          totalWins: 0,
          totalWinsLabel: '0',
          activeCount: 0,
          activeCountLabel: '0',
          totalDriversLabel: '0',
        }}
        empty={{
          title: 'No drivers found',
          description: 'There are no registered drivers in the system yet.'
        }}
      />
    );
  }

  const result = await DriversPageQuery.execute();

  if (result.isErr()) {
    const error = result.getError();
    if (error === 'NotFound') {
      redirect(routes.error.notFound);
    }
    return (
      <DriversPageClient
        viewData={null}
        error={true}
      />
    );
  }

  const viewData = result.unwrap();
  return (
    <DriversPageClient
      viewData={viewData}
    />
  );
}