export const LEARNITIVE_GIT_AUTHOR_NAME_STORAGE_KEY = 'interactive-git-author-name';
export const LEARNITIVE_GIT_AUTHOR_EMAIL_STORAGE_KEY = 'interactive-git-author-email';
export const LEARNITIVE_GIT_CORS_PROXY_STORAGE_KEY = 'interactive-git-cors-proxy';
const LEARNITIVE_GIT_CORS_PROXY_CONFIGURED_STORAGE_KEY = 'interactive-git-cors-proxy-r31-configured';

export const DEFAULT_LEARNITIVE_GIT_CORS_PROXY = 'https://cors.isomorphic-git.org';

export type BrowserGitSettings = {
  authorName: string;
  authorEmail: string;
  corsProxy: string;
};

function readLocalStorage(key: string): string | undefined {
  try {
    if (typeof globalThis.localStorage === 'undefined') return undefined;
    return globalThis.localStorage.getItem(key) ?? undefined;
  } catch {
    return undefined;
  }
}

function readBrowserGitCorsProxy(): string {
  const stored = readLocalStorage(LEARNITIVE_GIT_CORS_PROXY_STORAGE_KEY);
  const explicitlyConfigured =
    readLocalStorage(LEARNITIVE_GIT_CORS_PROXY_CONFIGURED_STORAGE_KEY) === '1';
  if (explicitlyConfigured) return stored?.trim() ?? '';

  // Before R31 the Git panel persisted its old empty default as soon as it was
  // opened. Treat that legacy empty value as "unset" so existing users receive
  // the new default. Preserve an existing non-empty custom proxy.
  return stored?.trim() || DEFAULT_LEARNITIVE_GIT_CORS_PROXY;
}

export function writeBrowserGitCorsProxySetting(value: string): void {
  try {
    if (typeof globalThis.localStorage === 'undefined') return;
    globalThis.localStorage.setItem(LEARNITIVE_GIT_CORS_PROXY_STORAGE_KEY, value);
    globalThis.localStorage.setItem(LEARNITIVE_GIT_CORS_PROXY_CONFIGURED_STORAGE_KEY, '1');
  } catch {
    // Browser privacy/storage policies may make local settings unavailable.
  }
}

export function readBrowserGitSettings(): BrowserGitSettings {
  return {
    authorName: readLocalStorage(LEARNITIVE_GIT_AUTHOR_NAME_STORAGE_KEY)?.trim() ?? '',
    authorEmail: readLocalStorage(LEARNITIVE_GIT_AUTHOR_EMAIL_STORAGE_KEY)?.trim() ?? '',
    corsProxy: readBrowserGitCorsProxy(),
  };
}

export function isDefaultPublicGitCorsProxy(value: string): boolean {
  return value.trim().replace(/\/+$/u, '') === DEFAULT_LEARNITIVE_GIT_CORS_PROXY;
}
