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

import { requireSupabaseAuth } from "@/integrations/supabase/auth-middleware";

/** Issue (or return) the UZIA certificate for a fully completed course. */
export const issueCertificate = createServerFn({ method: "POST" })
  .middleware([requireSupabaseAuth])
  .inputValidator((data: { courseId: string }) => data)
  .handler(async ({ data, context }) => {
    const { supabase, userId } = context;

    const existing = await supabase
      .from("certificates")
      .select("*")
      .eq("user_id", userId)
      .eq("course_id", data.courseId)
      .maybeSingle();
    if (existing.error) throw new Error(existing.error.message);
    if (existing.data) return { certificate: existing.data, created: false };

    const [course, profile, progress, result] = await Promise.all([
      supabase
        .from("courses")
        .select("id, title, credential_level, certificate_type, learning_hours, lessons")
        .eq("id", data.courseId)
        .maybeSingle(),
      supabase.from("profiles").select("full_name, business_name").eq("id", userId).maybeSingle(),
      supabase
        .from("course_progress")
        .select("lesson_index")
        .eq("user_id", userId)
        .eq("course_id", data.courseId),
      supabase
        .from("assessment_results")
        .select("overall_score")
        .eq("user_id", userId)
        .order("created_at", { ascending: false })
        .limit(1)
        .maybeSingle(),
    ]);
    if (course.error) throw new Error(course.error.message);
    if (progress.error) throw new Error(progress.error.message);
    if (!course.data) throw new Error("Course not found");

    const lessonCount = Array.isArray(course.data.lessons) ? course.data.lessons.length : 0;
    if (lessonCount === 0 || (progress.data ?? []).length < lessonCount) {
      throw new Error("Complete every module before claiming your certificate.");
    }

    const number = `UZIA-${new Date().getFullYear()}-${Math.random()
      .toString(36)
      .slice(2, 8)
      .toUpperCase()}`;

    const { data: created, error } = await supabase
      .from("certificates")
      .insert({
        user_id: userId,
        course_id: course.data.id,
        certificate_number: number,
        learner_name: profile.data?.full_name ?? "UZIA Learner",
        business_name: profile.data?.business_name ?? null,
        course_title: course.data.title,
        credential_level: course.data.credential_level,
        certificate_type: course.data.certificate_type,
        learning_hours: course.data.learning_hours,
        assessment_score: result.data?.overall_score ?? null,
      })
      .select("*")
      .single();
    if (error) throw new Error(error.message);

    return { certificate: created, created: true };
  });

export const listMyCertificates = createServerFn({ method: "GET" })
  .middleware([requireSupabaseAuth])
  .handler(async ({ context }) => {
    const { supabase, userId } = context;
    const { data, error } = await supabase
      .from("certificates")
      .select("*")
      .eq("user_id", userId)
      .order("issued_at", { ascending: false });
    if (error) throw new Error(error.message);
    return data ?? [];
  });

/** Public verification by certificate number, via a security-definer function. */
export const verifyCertificate = createServerFn({ method: "GET" })
  .inputValidator((data: { number: string }) => data)
  .handler(async ({ data }) => {
    const { getPublicClient } = await import("./public-client.server");
    const supabase = getPublicClient();
    const { data: rows, error } = await supabase.rpc("verify_certificate", {
      _number: data.number.trim().toUpperCase(),
    });
    if (error) throw new Error(error.message);
    return rows?.[0] ?? null;
  });
