import { API_BASE, FALLBACK_TENANT_ID, FALLBACK_USER_ID } from './constants'

export function getTenantId(): string {
  if (typeof window !== 'undefined') {
    return localStorage.getItem('sdk-tenant-id') || FALLBACK_TENANT_ID
  }
  return FALLBACK_TENANT_ID
}

export function getUserId(): string {
  if (typeof window !== 'undefined') {
    return localStorage.getItem('sdk-user-id') || FALLBACK_USER_ID
  }
  return FALLBACK_USER_ID
}

export function getDefaultRedirectUri(): string {
  if (typeof window !== 'undefined') {
    return `${window.location.origin}/api/sdk/v1/sso/oidc/callback`
  }
  return ''
}

export function formatDate(dateStr: string | null): string {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleDateString('de-DE', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  })
}

export async function apiFetch<T>(
  endpoint: string,
  options: RequestInit = {}
): Promise<T> {
  const res = await fetch(`${API_BASE}${endpoint}`, {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      'X-Tenant-ID': getTenantId(),
      'X-User-ID': getUserId(),
      ...options.headers,
    },
  })
  if (!res.ok) {
    const body = await res.json().catch(() => ({}))
    throw new Error(body.error || body.message || `HTTP ${res.status}`)
  }
  return res.json()
}
