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

export interface ManualEntryPayload {
    stock_instance_id?: string;
    symbol: string;
    active: boolean;
    user_id?: string;
    buy_price?: number | null;
    sell_price?: number | null;
    buy_time?: string | null;
    sell_time?: string | null;
    quantity?: number | null;
    filled_quantity?: number | null;
    notes?: string | null;
    status: string;
    is_crypto: boolean;
    is_real_trade: boolean;
    label?: string | null;
    entry_price?: number | null;
    gain_threshold_for_sell?: number | null;
    drop_threshold_for_buy?: number | null;
}

async function getAccessToken(): Promise<string> {
    return getPlatformAccessToken();
}

async function apiRequest<T>(path: string, init?: RequestInit): Promise<T> {
    const accessToken = await getAccessToken();
    const response = await fetch(`${tradingRuntime.tradingApiUrl}${path}`, {
        ...init,
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${accessToken}`,
            'x-request-id': createRequestId('web-entries'),
            ...(init?.headers || {}),
        },
    });

    const body = await response.json().catch(() => ({} as any));
    if (!response.ok) {
        throw new Error(body?.error || `Request failed (${response.status})`);
    }
    return body as T;
}

export async function fetchManualEntries(): Promise<ManualEntryPayload[]> {
    const response = await apiRequest<{ entries: ManualEntryPayload[] }>('/api/manual-entries');
    return Array.isArray(response.entries) ? response.entries : [];
}

export async function createManualEntry(payload: ManualEntryPayload): Promise<ManualEntryPayload> {
    const response = await apiRequest<{ entry: ManualEntryPayload }>('/api/manual-entries', {
        method: 'POST',
        body: JSON.stringify(payload),
    });
    return response.entry;
}

export async function updateManualEntry(id: string, payload: ManualEntryPayload): Promise<ManualEntryPayload> {
    const response = await apiRequest<{ entry: ManualEntryPayload }>(`/api/manual-entries/${id}`, {
        method: 'PUT',
        body: JSON.stringify(payload),
    });
    return response.entry;
}

export async function deleteManualEntry(id: string): Promise<void> {
    await apiRequest<{ success: boolean }>(`/api/manual-entries/${id}`, {
        method: 'DELETE',
    });
}
