import { supabase } from './supabaseClient';
import { tradingRuntime } from './runtime';

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

async function getAccessToken(): Promise<string> {
    const { data: sessionData } = await supabase.auth.getSession();
    const accessToken = sessionData.session?.access_token;
    if (!accessToken) {
        throw new Error('Not authenticated');
    }
    return accessToken;
}

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

    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 getAccessToken();
    const response = await fetch(`${tradingRuntime.tradingApiUrl}/api/admin/config/dynamic`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${accessToken}`,
        },
        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})`);
    }
}
