const clientApiUrl = (process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:3000').replace(/\/$/, '');

function getServerApiUrl() {
  return (process.env.INTERNAL_API_URL ?? process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:3000').replace(/\/$/, '');
}

export interface PublicSetting {
  key: string;
  value: string;
}

async function fetchWithTimeout(url: string, init: RequestInit & { timeoutMs?: number } = {}) {
  const { timeoutMs = 3000, ...rest } = init;
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), timeoutMs);
  try {
    return await fetch(url, { ...rest, signal: controller.signal });
  } finally {
    clearTimeout(timer);
  }
}

function mapSettings(payload: { settings?: PublicSetting[] }) {
  return Object.fromEntries((payload.settings ?? []).map((item) => [item.key, item.value]));
}

export async function fetchPublicSettings(): Promise<Record<string, string>> {
  try {
    const response = await fetchWithTimeout(`${getServerApiUrl()}/settings/public`, {
      cache: 'no-store'
    });
    if (!response.ok) {
      return {};
    }
    return mapSettings((await response.json()) as { settings?: PublicSetting[] });
  } catch {
    return {};
  }
}

export async function fetchPublicSettingsClient(): Promise<Record<string, string>> {
  const response = await fetchWithTimeout('/api/public-settings', { cache: 'no-store' });
  if (!response.ok) {
    throw new Error('Не удалось загрузить публичные настройки');
  }
  return mapSettings((await response.json()) as { settings?: PublicSetting[] });
}

export function getApiBaseUrl() {
  return clientApiUrl;
}

export function getDefaultProjectName() {
  return 'Lendry ID';
}

export function getDefaultProjectTagline() {
  return 'Единый аккаунт для сервисов Lendry';
}
