export type ApiAuthMode = 'auto' | 'none' | 'supabase' | 'legacy';

export type SupabaseAccessTokenProvider = () => Promise<string | null>;

async function defaultH5SupabaseAccessTokenProvider() {
  if (process.env.TARO_ENV !== 'h5') return null;
  const { getSupabaseAccessToken } = await import('./supabase');
  return getSupabaseAccessToken();
}

let supabaseAccessTokenProvider: SupabaseAccessTokenProvider = defaultH5SupabaseAccessTokenProvider;

export function setSupabaseAccessTokenProviderForTest(provider: SupabaseAccessTokenProvider | null) {
  supabaseAccessTokenProvider = provider || defaultH5SupabaseAccessTokenProvider;
}

export async function resolveApiAuthorization(input: {
  authMode?: ApiAuthMode;
  hasTokenOverride: boolean;
  explicitToken?: string | null;
  legacyToken?: string | null;
}) {
  const authMode = input.authMode || 'auto';
  if (authMode === 'none') return null;

  if (input.hasTokenOverride) {
    return input.explicitToken || null;
  }

  if (authMode === 'legacy') {
    return input.legacyToken || null;
  }

  const supabaseToken = await supabaseAccessTokenProvider();
  if (supabaseToken) return supabaseToken;

  if (authMode === 'supabase') return null;
  return input.legacyToken || null;
}

export function buildApiHeaders(input: {
  tenantId?: string | null;
  token?: string | null;
  extraHeaders?: Record<string, string>;
}) {
  const headers: Record<string, string> = {
    'content-type': 'application/json',
    ...(input.tenantId ? { 'x-tenant-id': input.tenantId } : {}),
    ...(input.token ? { authorization: `Bearer ${input.token}` } : {}),
  };

  for (const [key, value] of Object.entries(input.extraHeaders || {})) {
    const normalizedKey = key.toLowerCase();
    if (normalizedKey === 'authorization' || normalizedKey === 'x-tenant-id') {
      throw new Error(`Reserved API header cannot be overridden by page code: ${key}`);
    }
    headers[key] = value;
  }

  return headers;
}
