import { redirect } from 'next/navigation';
import { routes } from '@/lib/routing/RouteConfig';
import { DriverProfilePageQuery } from '@/lib/page-queries/DriverProfilePageQuery';
import { DriverProfilePageClient } from '@/client-wrapper/DriverProfilePageClient';
import { Metadata } from 'next';
import { MetadataHelper } from '@/lib/seo/MetadataHelper';
import { JsonLd } from '@/ui/JsonLd';

export async function generateMetadata({ params }: { params: Promise<{ id: string }> }): Promise<Metadata> {
  const { id } = await params;
  const result = await DriverProfilePageQuery.execute(id);

  if (result.isErr()) {
    return MetadataHelper.generate({
      title: 'Driver Not Found',
      description: 'The requested driver profile could not be found on GridPilot.',
      path: `/drivers/${id}`,
    });
  }

  const viewData = result.unwrap();
  const driver = viewData.currentDriver;

  if (!driver) {
    return MetadataHelper.generate({
      title: 'Driver Not Found',
      description: 'The requested driver profile could not be found on GridPilot.',
      path: `/drivers/${id}`,
    });
  }

  return MetadataHelper.generate({
    title: driver.name,
    description: driver.bio || `View the professional sim racing profile of ${driver.name} on GridPilot. Career statistics, race history, and performance metrics in the iRacing community.`,
    path: `/drivers/${id}`,
    image: driver.avatarUrl,
    type: 'profile',
  });
}

export default async function DriverProfilePage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const result = await DriverProfilePageQuery.execute(id);

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

  const viewData = result.unwrap();
  const driver = viewData.currentDriver;

  const jsonLd = driver ? {
    '@context': 'https://schema.org',
    '@type': 'Person',
    name: driver.name,
    description: driver.bio,
    image: driver.avatarUrl,
    url: `https://gridpilot.com/drivers/${driver.id}`,
    knowsAbout: ['Sim Racing', 'iRacing'],
  } : null;

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