"use client";

import { useSuspenseQuery } from "@tanstack/react-query";
import type { Course } from "../api/types";
import { notFound } from "next/navigation";
import CourseForm from "./course-form";
import { courseByIdOptions } from "../api/queries";

type CourseViewPageProps = {
  courseId: string;
};

export default function CourseViewPage({ courseId }: CourseViewPageProps) {
  if (courseId === "new") {
    return <CourseForm initialData={null} pageTitle="สร้างหลักสูตรใหม่" />;
  }

  return <EditCourseView courseId={Number(courseId)} />;
}

function EditCourseView({ courseId }: { courseId: number }) {
  const { data } = useSuspenseQuery(courseByIdOptions(courseId));

  if (!data?.success || !data?.course) {
    notFound();
  }

  return (
    <CourseForm initialData={data.course as Course} pageTitle="Edit Course" />
  );
}
