/**
 * cwProbabilityCache
 *
 * Fetches and caches the list of ConnectWise probability dropdown options.
 * Used to resolve a numeric percent (0–100) to the CW probability reference ID
 * required when creating or updating opportunities via the REST API.
 *
 * CW endpoint: GET /sales/probabilities
 * Returns: [{ id: number, probability: number }]
 */

import { connectWiseApi } from "../../../constants";

interface CWProbability {
    id: number;
    probability: number;
}

let _cache: CWProbability[] | null = null;

async function fetchProbabilities(): Promise<CWProbability[]> {
    if (_cache) return _cache;
    const response = await connectWiseApi.get<CWProbability[]>(
        "/sales/probabilities",
        { params: { pageSize: 1000 } }
    );
    _cache = response.data;
    return _cache;
}

/**
 * Resolve the CW probability reference ID for a given percent value.
 *
 * Finds an exact match first; if none, returns the closest option.
 * Returns null if the probabilities list is empty.
 */
export async function resolveCwProbabilityId(
    percent: number
): Promise<number | null> {
    const list = await fetchProbabilities();
    if (list.length === 0) return null;

    // Exact match
    const exact = list.find((p) => p.probability === percent);
    if (exact) return exact.id;

    // Closest match
    let closest = list[0]!;
    let minDiff = Math.abs(closest.probability - percent);
    for (const option of list) {
        const diff = Math.abs(option.probability - percent);
        if (diff < minDiff) {
            minDiff = diff;
            closest = option;
        }
    }
    return closest.id;
}

/** Clear the cache (useful for tests or forced refresh). */
export function clearCwProbabilityCache(): void {
    _cache = null;
}
