const API = process.env.REACT_APP_API_URL || '/api';

const getHeaders = () => ({
    Authorization: `Bearer ${localStorage.getItem('token')}`,
});

export const createShare = async (formData) => {
    const res = await fetch(`${API}/shares`, {
        method: 'POST',
        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` },
        body: formData, // FormData — kein Content-Type Header setzen!
    });
    if (!res.ok) {
        const err = await res.json();
        throw new Error(err.error || 'Fehler beim Erstellen');
    }
    return res.json();
};

export const getAllShares = async () => {
    const res = await fetch(`${API}/shares`, { headers: getHeaders() });
    if (!res.ok) throw new Error('Fehler beim Laden');
    return res.json();
};

export const deleteShare = async (id) => {
    const res = await fetch(`${API}/shares/${id}`, {
        method: 'DELETE',
        headers: getHeaders(),
    });
    if (!res.ok) throw new Error('Fehler beim Löschen');
    return res.json();
};

export const getPublicShare = async (token) => {
    const res = await fetch(`${API}/shares/public/${token}`);
    if (!res.ok) {
        const err = await res.json();
        throw new Error(err.error || 'Nicht gefunden');
    }
    return res.json();
};

export const accessShare = async (token, password) => {
    const res = await fetch(`${API}/shares/public/${token}/access`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ password }),
    });
    if (!res.ok) {
        const err = await res.json();
        throw new Error(err.error || 'Zugriff verweigert');
    }
    return res.json();
};

export const getFileDownloadUrl = (token, password) => {
    const base = `${API}/shares/public/${token}/file`;
    return password ? `${base}?password=${encodeURIComponent(password)}` : base;
};
