import { getToken, setToken } from '../utils/session.js';

/**
 * Multipart upload helper. Do not set Content-Type manually — the browser
 * must add the multipart boundary.
 */
export async function uploadFormData(url, formData, method = 'POST') {
    const headers = new Headers();
    const token = getToken();
    if (token) {
        headers.append('Authorization', `Bearer ${token}`);
    }

    const res = await fetch(url, {
        method,
        headers,
        body: formData,
    });

    let data = null;
    try {
        data = await res.json();
    } catch {
        data = null;
    }

    if (res.ok) {
        const newToken = res.headers.get('Auth-Token');
        if (newToken) {
            setToken(newToken);
        }
    }

    return { data, success: res.ok };
}
