import { getPlatformAccessToken } from './authSession';
import { tradingRuntime } from './runtime';
import { createRequestId } from '../../../shared/request-id.js';

export interface DynamicConfigItem {
    key: string;
    value: string;
    description: string;
}

export async function fetchDynamicConfigItems(): Promise<DynamicConfigItem[]> {
    const accessToken = await getPlatformAccessToken();
    const response = await fetch(`${tradingRuntime.tradingApiUrl}/api/admin/config/dynamic`, {
        headers: {
            Authorization: `Bearer ${accessToken}`,
            'x-request-id': createRequestId('web-config'),
        },
    });

    const body = await response.json().catch(() => ({} as any));
    if (!response.ok) {
        throw new Error(body?.error || `Failed to load dynamic config (${response.status})`);
    }

    return Array.isArray(body?.items) ? (body.items as DynamicConfigItem[]) : [];
}

export async function upsertDynamicConfigItems(items: DynamicConfigItem[]): Promise<void> {
    const accessToken = await getPlatformAccessToken();
    const response = await fetch(`${tradingRuntime.tradingApiUrl}/api/admin/config/dynamic`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${accessToken}`,
            'x-request-id': createRequestId('web-config'),
        },
        body: JSON.stringify({ items }),
    });

    const body = await response.json().catch(() => ({} as any));
    if (!response.ok || body?.success === false) {
        throw new Error(body?.error || `Failed to update dynamic config (${response.status})`);
    }
}
