import { ZyphonAdminClient } from '@zyphon/api-client';

/**
 * Browser: same-origin `/api` rewrite → gateway `/admin/*` (cookies + CSRF).
 * Server: direct internal admin URL.
 */
const baseUrl =
  typeof window !== 'undefined'
    ? '/api'
    : (process.env.INTERNAL_GATEWAY_URL || 'http://127.0.0.1:8081');

export const adminClient = new ZyphonAdminClient({
  baseUrl,
});

const TOKEN_KEY = 'zyphon_admin_token';
const CSRF_KEY = 'zyphon_csrf_token';

if (typeof window !== 'undefined') {
  const token = localStorage.getItem(TOKEN_KEY);
  if (token) {
    adminClient.setToken(token);
  }
  const csrf = localStorage.getItem(CSRF_KEY);
  if (csrf) {
    adminClient.setCsrfToken(csrf);
  }
}

export function saveAdminToken(token: string, csrfToken?: string): void {
  if (typeof window === 'undefined') return;
  localStorage.setItem(TOKEN_KEY, token);
  adminClient.setToken(token);
  if (csrfToken) {
    localStorage.setItem(CSRF_KEY, csrfToken);
    adminClient.setCsrfToken(csrfToken);
  }
}

export async function adminLogin(password: string): Promise<{ success: boolean; role?: string }> {
  const data = await adminClient.login(password);
  if (data.token) {
    saveAdminToken(data.token, data.csrfToken);
    // Prefer non-httpOnly CSRF cookie when the gateway set one
    if (typeof document !== 'undefined' && !data.csrfToken) {
      const match = document.cookie.match(/(?:^|;\s*)zyphon_csrf=([^;]+)/);
      if (match?.[1]) {
        saveAdminToken(data.token, decodeURIComponent(match[1]));
      }
    }
  }
  return { success: data.success, role: data.role };
}

export function clearAdminToken(): void {
  if (typeof window === 'undefined') return;
  localStorage.removeItem(TOKEN_KEY);
  localStorage.removeItem(CSRF_KEY);
  adminClient.setToken('');
  adminClient.setCsrfToken('');
}
