import { notFound, redirect } from 'next/navigation';
import { LeaderboardsPageQuery } from '@/lib/page-queries/LeaderboardsPageQuery';
import { LeaderboardsPageClient } from '@/client-wrapper/LeaderboardsPageClient';
import { routes } from '@/lib/routing/RouteConfig';
import { logger } from '@/lib/infrastructure/logging/logger';
import { Metadata } from 'next';
import { MetadataHelper } from '@/lib/seo/MetadataHelper';
import { JsonLd } from '@/ui/JsonLd';

export const metadata: Metadata = MetadataHelper.generate({
  title: 'Global Leaderboards',
  description: 'Global performance rankings for drivers and teams on GridPilot. Comprehensive leaderboards featuring competitive results and career statistics.',
  path: '/leaderboards',
});

export default async function LeaderboardsPage() {
  const result = await LeaderboardsPageQuery.execute();

  if (result.isErr()) {
    const error = result.getError();

    // Handle different error types
    if (error === 'notFound') {
      notFound();
    } else if (error === 'redirect') {
      redirect(routes.public.home);
    } else {
      // serverError, networkError, unknown, validationError, unauthorized
      logger.error('Leaderboards error:', undefined, { error });
      notFound();
    }
  }

  // Success
  const viewData = result.unwrap();

  const jsonLd = {
    '@context': 'https://schema.org',
    '@type': 'ItemList',
    name: 'Global Driver Leaderboard',
    description: 'Top performing sim racing drivers on GridPilot',
    itemListElement: viewData.drivers.slice(0, 10).map((d, i) => ({
      '@type': 'ListItem',
      position: i + 1,
      item: {
        '@type': 'Person',
        name: d.name,
        url: `https://gridpilot.com/drivers/${d.id}`,
      },
    })),
  };

  return (
    <>
      <JsonLd data={jsonLd} />
      <LeaderboardsPageClient viewData={viewData} />
    </>
  );
}
