import { Language, TranslationKeys } from './types';
import { getApiBaseUrl } from '../../config/config';

export interface I18nCodeInfo {
    code: string;
    label?: string;
    status?: string;
    isDefault?: boolean;
    entriesCount?: number;
}

interface I18nEntryRaw {
    context?: string;
    key: string;
    value: string;
}

export async function fetchAvailableLanguageCodes(): Promise<I18nCodeInfo[]> {
    const base = getApiBaseUrl().replace(/\/$/, '');
    const res = await fetch(`${base}/api/i18n/codes`, { credentials: 'include' });
    if (!res.ok) {
        throw new Error(`i18n/codes failed: ${res.status}`);
    }
    return res.json();
}

export const loadLanguage = async (language: Language): Promise<TranslationKeys> => {
    const base = getApiBaseUrl().replace(/\/$/, '');
    const code = String(language || 'de').trim() || 'de';
    const res = await fetch(`${base}/api/i18n/sets/${encodeURIComponent(code)}`, {
        credentials: 'include',
    });
    if (!res.ok) {
        throw new Error(`Failed to load language ${code}: ${res.status}`);
    }
    const data = await res.json();

    if (Array.isArray(data.entries)) {
        const map: TranslationKeys = {};
        for (const e of data.entries as I18nEntryRaw[]) {
            if (e.key) map[e.key] = e.value ?? '';
        }
        return map;
    }

    if (data.keys && typeof data.keys === 'object') {
        return data.keys as TranslationKeys;
    }

    return {};
};

export type { Language, TranslationKeys } from './types';
