import type { Metadata } from "next";
import { getQuestion } from "@/lib/api";
import { QuestionDetail } from "@/components/questions/question-detail";
import { ProblemWorkspace } from "@/components/editor";
import { notFound } from "next/navigation";

interface PageProps {
  params: Promise<{ slug: string }>;
}

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const { slug } = await params;

  try {
    const question = await getQuestion(slug);
    const description = question.description
      .replace(/[#*`]/g, "")
      .substring(0, 160)
      .trim();

    return {
      title: question.title,
      description,
      openGraph: {
        title: `${question.title} | CodeTutor`,
        description,
        type: "article",
      },
    };
  } catch {
    return {
      title: "Question Not Found",
    };
  }
}

export default async function QuestionDetailPage({ params }: PageProps) {
  const { slug } = await params;

  let question;
  try {
    question = await getQuestion(slug);
  } catch {
    notFound();
  }

  // Show interactive workspace if the question has test cases
  if (question.function_signature && question.visible_test_cases) {
    return <ProblemWorkspace question={question} />;
  }

  // Fall back to read-only view for questions without test cases
  return <QuestionDetail question={question} />;
}
