import type { Metadata } from 'next';

interface PackageSummary {
  id: string;
  name: string;
  description?: string | null;
  outboundSchedule?: {
    originStation?: { name?: string };
    destinationStation?: { name?: string };
  };
}

/**
 * Fetch a minimal package summary server-side so we can generate per-package
 * metadata without requiring the page itself to be a Server Component.
 * Errors are swallowed so the page still renders even if the API is unreachable
 * at build/request time.
 */
async function fetchPackageSummary(id: string): Promise<PackageSummary | null> {
  try {
    const apiUrl = process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:4000';
    const res = await fetch(`${apiUrl}/packages/${id}`, {
      next: { revalidate: 3600 },
    });
    if (!res.ok) return null;
    return await res.json();
  } catch {
    return null;
  }
}

export async function generateMetadata({
  params,
}: {
  params: { id: string };
}): Promise<Metadata> {
  const pkg = await fetchPackageSummary(params.id);

  if (!pkg) {
    return {
      title: 'Train Package – EDR',
      description:
        'View details and book this Ethio-Djibouti Railway travel package with seat selection and flexible payment options.',
      robots: { index: true, follow: true },
    };
  }

  const origin = pkg.outboundSchedule?.originStation?.name?.trim();
  const destination = pkg.outboundSchedule?.destinationStation?.name?.trim();
  const routeLabel = origin && destination ? ` – ${origin} to ${destination}` : '';
  const title = `${pkg.name}${routeLabel} | EDR`;
  const description =
    pkg.description?.trim() ||
    `Book the "${pkg.name}" train package on the Ethio-Djibouti Railway${routeLabel ? ` (${origin} → ${destination})` : ''}. Choose your seat class and complete payment online.`;

  return {
    title,
    description,
    alternates: {
      canonical: `/packages/${params.id}`,
    },
    openGraph: {
      title,
      description,
      url: `/packages/${params.id}`,
      images: [
        {
          url: '/edr-banner.jpg',
          width: 1200,
          height: 630,
          alt: `EDR Railway – ${pkg.name}`,
        },
      ],
    },
  };
}

export default function PackageDetailLayout({ children }: { children: React.ReactNode }) {
  return children;
}
