import { createClient as createSupabaseClient } from "@supabase/supabase-js";
import { COOKIE_DO_VINCULO, retornoQueOSupabaseAceita } from "@/lib/passagem-do-login";

/*
  O comeco do login com o Google, igual para os dois botoes da loja (a tela
  de entrar e a janela de login da vitrine). Roda no navegador.

  O Google devolve sempre no endereco principal. Quando a loja esta num
  dominio proprio, o retorno leva junto a origem da loja e um vinculo com este
  navegador; o endereco principal entrega uma passagem e a sessao volta para
  ca, onde esta o carrinho (ver lib/passagem-do-login.ts e a migration 163).
*/

function origemDoRetorno() {
  const { origin, hostname } = window.location;
  if (hostname === "localhost" || hostname === "127.0.0.1") return origin;
  const configurada = String(process.env.NEXT_PUBLIC_PUBLIC_CATALOG_BASE_URL || "").trim();
  if (!configurada) return origin;
  try {
    return new URL(configurada).origin;
  } catch {
    return origin;
  }
}

/* Um segredo novo a cada login, gravado num cookie deste dominio. Vale 15
   minutos: o tempo de escolher a conta no Google com folga. */
function novoVinculo() {
  const bytes = new Uint8Array(24);
  window.crypto.getRandomValues(bytes);
  const vinculo = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
  const seguro = window.location.protocol === "https:" ? "; Secure" : "";
  document.cookie = `${COOKIE_DO_VINCULO}=${vinculo}; Path=/; Max-Age=900; SameSite=Lax${seguro}`;
  return vinculo;
}

export async function entrarComGoogle({ slug, next }: { slug: string; next?: string | null }) {
  const url = process.env.NEXT_PUBLIC_SUPABASE_URL;
  const anon = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
  if (!url || !anon) {
    throw new Error("Supabase env vars are missing.");
  }

  const cliente = createSupabaseClient(url, anon, {
    auth: {
      flowType: "implicit",
      autoRefreshToken: false,
      persistSession: false,
      detectSessionInUrl: false,
    },
  });

  const retorno = new URL("/oauth/client-portal", origemDoRetorno());
  retorno.searchParams.set("slug", slug);
  if (next) retorno.searchParams.set("next", next);
  if (retorno.origin !== window.location.origin) {
    retorno.searchParams.set("origem", window.location.origin);
    retorno.searchParams.set("vinculo", novoVinculo());
  }

  const { data, error } = await cliente.auth.signInWithOAuth({
    provider: "google",
    options: {
      redirectTo: retornoQueOSupabaseAceita(retorno),
      skipBrowserRedirect: true,
    },
  });
  if (error) throw error;
  if (!data?.url) {
    throw new Error("Não foi possível iniciar o login com Google.");
  }
  window.location.assign(data.url);
}
