import { createServerFn } from "@tanstack/react-start";
import { requireSupabaseAuth } from "@/integrations/supabase/auth-middleware";

/** The signed-in user's plan, membership category and free-tier usage. */
export const getMyPlan = createServerFn({ method: "GET" })
  .middleware([requireSupabaseAuth])
  .handler(async ({ context }) => {
    const { supabase, userId } = context;

    const [profile, results, requests] = await Promise.all([
      supabase
        .from("profiles")
        .select("plan_tier, membership_category, member_reference, plan_activated_at")
        .eq("id", userId)
        .maybeSingle(),
      supabase.from("assessment_results").select("id").eq("user_id", userId),
      supabase
        .from("plan_upgrade_requests")
        .select("id, plan, amount_kes, payment_method, status, created_at")
        .eq("user_id", userId)
        .order("created_at", { ascending: false })
        .limit(5),
    ]);
    if (profile.error) throw new Error(profile.error.message);
    if (results.error) throw new Error(results.error.message);
    if (requests.error) throw new Error(requests.error.message);

    const tier = profile.data?.plan_tier ?? "free";
    const resultCount = results.data?.length ?? 0;

    return {
      tier,
      isPro: tier === "pro" || tier === "team",
      membershipCategory: profile.data?.membership_category ?? "marketplace",
      memberReference: profile.data?.member_reference ?? null,
      planActivatedAt: profile.data?.plan_activated_at ?? null,
      resultCount,
      assessmentsRemaining: tier === "free" ? Math.max(0, 1 - resultCount) : null,
      pendingRequests: (requests.data ?? []).filter((r) => r.status === "pending"),
      requests: requests.data ?? [],
    };
  });

export const requestUpgrade = createServerFn({ method: "POST" })
  .middleware([requireSupabaseAuth])
  .inputValidator(
    (data: {
      plan: string;
      membership_category: string;
      amount_kes: number;
      payment_method: string;
      payment_reference: string;
      contact_email?: string;
      contact_phone?: string;
      notes?: string;
    }) => {
      const trimmed = data.payment_reference?.trim() ?? "";
      if (trimmed.length < 4 || trimmed.length > 120) {
        throw new Error("Enter the payment reference from your receipt (4-120 characters).");
      }
      return { ...data, payment_reference: trimmed };
    },
  )
  .handler(async ({ data, context }) => {
    const { supabase, userId } = context;
    const { error } = await supabase.from("plan_upgrade_requests").insert({
      user_id: userId,
      plan: data.plan.slice(0, 60),
      membership_category: data.membership_category.slice(0, 40),
      amount_kes: Math.max(0, Math.round(data.amount_kes)),
      payment_method: data.payment_method.slice(0, 40),
      payment_reference: data.payment_reference,
      contact_email: data.contact_email?.slice(0, 255) ?? null,
      contact_phone: data.contact_phone?.slice(0, 40) ?? null,
      notes: data.notes?.slice(0, 1000) ?? null,
    });
    if (error) throw new Error(error.message);
    return { ok: true };
  });
