import { notFound } from "next/navigation";
import { Vacancy } from "@/types";
import VacancyClientContent from "../_components/VacancyClientContent";

interface ExtendedVacancy extends Vacancy {
  company?: {
    name: string;
    logoUrl?: string;
    websiteUrl?: string;
  };
  skills?: string[];
}

async function getVacancy(slug: string): Promise<ExtendedVacancy | null> {
  const res = await fetch(`http://localhost:3000/api/vacancies/${slug}`, {
    cache: "no-store",
  });
  if (!res.ok) {
    if (res.status === 404) return null;
    console.error(`Failed to fetch vacancy ${slug}: ${res.statusText}`);
    throw new Error("Failed to fetch vacancy details");
  }
  return res.json();
}

export default async function VacancyDetailsPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const vacancy = await getVacancy(slug);

  if (!vacancy) {
    notFound();
  }

  const shareUrl = `${process.env.WEBSITE_URL}/vacancies/${slug}`;
  const shareTitle = encodeURIComponent(
    `Job Opening: ${vacancy.title} at ${
      vacancy.company?.name || "Owethu Managed Services"
    }`
  );

  return (
    <div className="bg-white dark:bg-black text-gray-800 font-poppins overflow-x-hidden min-h-screen py-12 md:py-5">
      <VacancyClientContent
        vacancy={vacancy}
        shareUrl={shareUrl}
        shareTitle={shareTitle}
      />
    </div>
  );
}
