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

const supabaseUrl = import.meta.env.VITE_SUPABASE_URL?.trim() ?? '';
const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY?.trim() ?? '';
const sourceFilesBucket = import.meta.env.VITE_SUPABASE_SOURCE_FILES_BUCKET?.trim() || 'source-files';

function getSupabaseProjectRef() {
  if (!supabaseUrl) {
    return null;
  }

  try {
    const [projectRef] = new URL(supabaseUrl).hostname.split('.');
    return projectRef || null;
  } catch {
    return null;
  }
}

function shouldClearSupabaseAuthKey(key: string, projectRef: string | null) {
  if (projectRef) {
    return key === `sb-${projectRef}-auth-token`
      || key.startsWith(`sb-${projectRef}-auth-token-`)
      || key === `sb-${projectRef}-code-verifier`
      || key.startsWith(`sb-${projectRef}-code-verifier`);
  }

  return key.startsWith('sb-') && (key.includes('-auth-token') || key.includes('code-verifier'));
}

export function isSupabaseConfigured() {
  return Boolean(supabaseUrl && supabaseAnonKey);
}

export function clearSupabaseAuthStorage() {
  if (typeof window === 'undefined') {
    return;
  }

  const storage = window.localStorage;
  const projectRef = getSupabaseProjectRef();
  const keysToRemove: string[] = [];

  for (let index = 0; index < storage.length; index += 1) {
    const key = storage.key(index);
    if (key && shouldClearSupabaseAuthKey(key, projectRef)) {
      keysToRemove.push(key);
    }
  }

  keysToRemove.forEach(key => {
    storage.removeItem(key);
  });
}

let supabaseClient: SupabaseClient | null = null;

if (isSupabaseConfigured()) {
  supabaseClient = createClient(supabaseUrl, supabaseAnonKey, {
    auth: {
      persistSession: true,
      autoRefreshToken: true,
    },
  });
}

export function getSupabaseClient() {
  if (!supabaseClient) {
    throw new Error('Supabase 环境变量未配置，请先设置 VITE_SUPABASE_URL 和 VITE_SUPABASE_ANON_KEY。');
  }

  return supabaseClient;
}

export { sourceFilesBucket };