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

export const getMyProfile = createServerFn({ method: "GET" })
  .middleware([requireSupabaseAuth])
  .handler(async ({ context }) => {
    const { supabase, userId } = context;
    const { data, error } = await supabase
      .from("profiles")
      .select("*")
      .eq("id", userId)
      .maybeSingle();
    if (error) throw new Error(error.message);
    return data;
  });

export const updateMyProfile = createServerFn({ method: "POST" })
  .middleware([requireSupabaseAuth])
  .inputValidator(
    (data: {
      full_name: string;
      business_name: string;
      sector: string;
      business_size: string;
      county: string;
      membership_category: string;
      member_reference: string;
    }) => {
      const trim = (v: string, max: number) => (v ?? "").trim().slice(0, max);
      return {
        full_name: trim(data.full_name, 120),
        business_name: trim(data.business_name, 160),
        sector: trim(data.sector, 80),
        business_size: trim(data.business_size, 60),
        county: trim(data.county, 80),
        membership_category: ["marketplace", "incubator", "donor"].includes(
          data.membership_category,
        )
          ? data.membership_category
          : "marketplace",
        member_reference: trim(data.member_reference, 120),
      };
    },
  )
  .handler(async ({ data, context }) => {
    const { supabase, userId } = context;
    const { error } = await supabase
      .from("profiles")
      .upsert({ id: userId, ...data }, { onConflict: "id" });
    if (error) throw new Error(error.message);
    return { ok: true };
  });

/** Store the uploaded avatar path and return a fresh signed preview URL. */
export const setMyAvatar = createServerFn({ method: "POST" })
  .middleware([requireSupabaseAuth])
  .inputValidator((data: { path: string }) => {
    if (!data.path || data.path.length > 300) throw new Error("Invalid avatar path");
    return data;
  })
  .handler(async ({ data, context }) => {
    const { supabase, userId } = context;
    if (!data.path.startsWith(`${userId}/`)) throw new Error("Invalid avatar path");

    const { error } = await supabase
      .from("profiles")
      .upsert({ id: userId, avatar_url: data.path }, { onConflict: "id" });
    if (error) throw new Error(error.message);

    const signed = await supabase.storage.from("avatars").createSignedUrl(data.path, 60 * 60);
    return { path: data.path, url: signed.data?.signedUrl ?? null };
  });

/** Signed URL for the current user's stored avatar, if any. */
export const getMyAvatarUrl = createServerFn({ method: "GET" })
  .middleware([requireSupabaseAuth])
  .handler(async ({ context }) => {
    const { supabase, userId } = context;
    const { data } = await supabase
      .from("profiles")
      .select("avatar_url")
      .eq("id", userId)
      .maybeSingle();
    if (!data?.avatar_url) return { url: null };
    const signed = await supabase.storage
      .from("avatars")
      .createSignedUrl(data.avatar_url, 60 * 60);
    return { url: signed.data?.signedUrl ?? null };
  });
