const API_BASE = "http://localhost:8000/api";

export async function searchStock(query: string) {
    const res = await fetch(`${API_BASE}/search`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ query }),
    });
    if (!res.ok) throw new Error("Search failed");
    return res.json() as Promise<{ market: string; symbol: string; company_name: string }[]>;
}

export async function startAnalysis(market: string, symbol: string, company_name: string) {
    const res = await fetch(`${API_BASE}/analyze`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ market, symbol, company_name }),
    });
    if (!res.ok) {
        const error = await res.json();
        throw new Error(error.detail || "Analysis failed");
    }
    return res.json();
}

export async function getReports() {
    const res = await fetch(`${API_BASE}/reports`);
    if (!res.ok) throw new Error("Failed to fetch reports");
    return res.json();
}

export async function getReport(id: number) {
    const res = await fetch(`${API_BASE}/reports/${id}`);
    if (!res.ok) throw new Error("Failed to fetch report");
    return res.json();
}

export async function getConfig() {
    const res = await fetch(`${API_BASE}/config`);
    if (!res.ok) throw new Error("Failed to fetch config");
    return res.json();
}

export async function updateConfig(key: string, value: string) {
    const res = await fetch(`${API_BASE}/config`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ key, value }),
    });
    if (!res.ok) throw new Error("Failed to update config");
    return res.json();
}
