import { createServerFn } from "@tanstack/react-start";

const COURSE_FIELDS =
  "id, slug, title, summary, category_slug, level, duration_minutes, duration_weeks, learning_hours, price_kes, credential_level, certificate_type, group_code, group_name, domain_code, is_premium, lessons, sort_order";

export const listCourses = createServerFn({ method: "GET" }).handler(async () => {
  const { getPublicClient } = await import("./public-client.server");
  const supabase = getPublicClient();
  const { data, error } = await supabase
    .from("courses")
    .select(COURSE_FIELDS)
    .order("sort_order", { ascending: true });
  if (error) throw new Error(error.message);
  return data ?? [];
});

export const listCategories = createServerFn({ method: "GET" }).handler(async () => {
  const { getPublicClient } = await import("./public-client.server");
  const supabase = getPublicClient();
  const { data, error } = await supabase
    .from("assessment_categories")
    .select("id, slug, code, name, description, sort_order")
    .order("sort_order", { ascending: true });
  if (error) throw new Error(error.message);
  return data ?? [];
});

export const getCourseBySlug = createServerFn({ method: "GET" })
  .inputValidator((data: { slug: string }) => data)
  .handler(async ({ data }) => {
    const { getPublicClient } = await import("./public-client.server");
    const supabase = getPublicClient();
    const { data: course, error } = await supabase
      .from("courses")
      .select("*")
      .eq("slug", data.slug)
      .maybeSingle();
    if (error) throw new Error(error.message);
    return course;
  });
