import type { Metadata } from 'next';
import CareersJobDetailClient from './CareersJobDetailClient';

const CAREERS_API = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000/api/v1';
const SITE_ORIGIN = (process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000').replace(/\/$/, '');

async function getJob(id: string) {
  try {
    const res = await fetch(`${CAREERS_API}/public/jobs/${id}/`, { cache: 'no-store' });
    if (!res.ok) return null;
    const body = await res.json();
    return body?.data ?? body ?? null;
  } catch {
    return null;
  }
}

// Server-rendered Open Graph tags so a shared link (LinkedIn, WhatsApp, X…)
// unfurls into a rich card with the gradient banner from ./opengraph-image.
export async function generateMetadata({ params }: { params: Promise<{ id: string }> }): Promise<Metadata> {
  const { id } = await params;
  const job = await getJob(id);
  const title = job?.title ? `${job.title} — We're hiring` : 'Job opening';
  const bits = [job?.client_name, job?.location, job?.experience_band].filter(Boolean).join(' · ');
  const skills = job?.must_have_skills ? `Key skills: ${job.must_have_skills}` : '';
  const description = [bits, skills].filter(Boolean).join(' — ') || 'View this opening and apply.';
  const url = `${SITE_ORIGIN}/careers/jobs/${id}`;
  return {
    metadataBase: new URL(SITE_ORIGIN),
    title,
    description,
    openGraph: { title, description, url, type: 'website' },
    twitter: { card: 'summary_large_image', title, description },
  };
}

export default function CareersJobDetailPage() {
  return <CareersJobDetailClient />;
}
