import type { SupabaseClient } from "@supabase/supabase-js";

export type OrganizationMember = {
  avatar_url: string | null;
  created_at: string;
  email: string | null;
  first_name: string | null;
  id: string;
  last_name: string | null;
  name: string | null;
  plan: string | null;
};

type LoadOrganizationMembersOptions = {
  organizationId: number;
  userId: string;
};

const organizationMemberSelect =
  "id, email, name, first_name, last_name, avatar_url, created_at, plan";

export const loadOrganizationMembers = async (
  supabase: SupabaseClient,
  { organizationId, userId }: LoadOrganizationMembersOptions
) => {
  const { data, error } = await supabase
    .from("profiles")
    .select(organizationMemberSelect)
    .eq("organization_id", organizationId)
    .order("created_at", { ascending: true });

  if (!error) {
    return {
      data: (data as OrganizationMember[] | null) ?? [],
      error: null,
    };
  }

  const fallback = await supabase
    .from("profiles")
    .select(organizationMemberSelect)
    .eq("id", userId)
    .single();

  if (fallback.error || !fallback.data) {
    return {
      data: null,
      error: fallback.error ?? error,
    };
  }

  return {
    data: [fallback.data as OrganizationMember],
    error: null,
  };
};
