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

export type GlmUser = {
  id: string;
  name: string;
  firstName: string;
  email: string;
  initials: string;
  avatarUrl: string | null;
};

let browserClient: SupabaseClient | null = null;

function requiredEnv(name: "VITE_SUPABASE_URL" | "VITE_SUPABASE_ANON_KEY") {
  const raw = import.meta.env[name];
  const value = typeof raw === "string" ? raw.trim() : "";
  if (!value) {
    throw new Error(`Falta configurar ${name} en el archivo .env.`);
  }
  return value;
}

export function getSupabaseClient() {
  if (typeof window === "undefined") {
    throw new Error("El cliente de Supabase solo debe inicializarse en el navegador.");
  }

  if (!browserClient) {
    browserClient = createClient(
      requiredEnv("VITE_SUPABASE_URL"),
      requiredEnv("VITE_SUPABASE_ANON_KEY"),
      {
        auth: {
          autoRefreshToken: true,
          detectSessionInUrl: true,
          persistSession: true,
          flowType: "pkce",
        },
      },
    );
  }

  return browserClient;
}

export function getAuthRedirectUrl() {
  if (typeof window === "undefined") return import.meta.env.BASE_URL;
  return new URL(import.meta.env.BASE_URL, window.location.origin).toString();
}

export function toGlmUser(user: User): GlmUser {
  const metadata = user.user_metadata ?? {};
  const email = user.email ?? "";
  const name =
    (typeof metadata["full_name"] === "string" && metadata["full_name"].trim()) ||
    (typeof metadata["name"] === "string" && metadata["name"].trim()) ||
    email.split("@")[0] ||
    "Usuario GLM";

  const nameParts = name.split(/\s+/).filter(Boolean);
  const givenName =
    (typeof metadata["given_name"] === "string" && metadata["given_name"].trim()) ||
    nameParts[0] ||
    "Usuario";
  const familyName =
    (typeof metadata["family_name"] === "string" && metadata["family_name"].trim()) ||
    (nameParts.length > 1 ? nameParts[nameParts.length - 1] : "");
  const firstName = givenName.split(/\s+/).filter(Boolean)[0] || nameParts[0] || "Usuario";
  const firstFamilyName = familyName.split(/\s+/).filter(Boolean)[0] || "";
  const initials =
    `${firstName[0]?.toUpperCase() ?? ""}${firstFamilyName[0]?.toUpperCase() ?? ""}` || "GL";

  const avatarUrl =
    (typeof metadata["avatar_url"] === "string" && metadata["avatar_url"].trim()) ||
    (typeof metadata["picture"] === "string" && metadata["picture"].trim()) ||
    null;

  return { id: user.id, name, firstName, email, initials, avatarUrl };
}
