// Lightweight auth service to manage tokens and API calls

// Use proxy in development, direct API in production
const API_URL = import.meta.env.VITE_API_URL || (import.meta.env.DEV ? '' : 'https://api.konturai.kz');

const TOKEN_STORAGE_KEY = 'auth.accessToken';
const REFRESH_STORAGE_KEY = 'auth.refreshToken';

function getAccessToken() {
    return localStorage.getItem(TOKEN_STORAGE_KEY) || '';
}

function getRefreshToken() {
    return localStorage.getItem(REFRESH_STORAGE_KEY) || '';
}

function setTokens(accessToken, refreshToken) {
    if (accessToken) localStorage.setItem(TOKEN_STORAGE_KEY, accessToken);
    if (refreshToken) localStorage.setItem(REFRESH_STORAGE_KEY, refreshToken);
}

function clearTokens() {
    localStorage.removeItem(TOKEN_STORAGE_KEY);
    localStorage.removeItem(REFRESH_STORAGE_KEY);
}

async function signin(email, password) {
    const res = await fetch(`${API_URL}/api/auth/signin`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password })
    });
    if (!res.ok) {
        let message = 'Sign in failed';
        try {
            const data = await res.json();
            message = data.message || message;
        } catch (_) {}
        throw new Error(message);
    }
    const data = await res.json();
    setTokens(data.accessToken, data.refreshToken);
    return data;
}

async function refreshToken() {
    const refresh = getRefreshToken();
    if (!refresh) throw new Error('No refresh token');
    const res = await fetch(`${API_URL}/api/auth/refresh`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ refreshToken: refresh })
    });
    if (!res.ok) throw new Error('Refresh failed');
    const data = await res.json();
    setTokens(data.accessToken, data.refreshToken);
    return data.accessToken;
}

async function logout() {
    try {
        await fetch(`${API_URL}/api/auth/logout`, { method: 'POST', headers: { 'Content-Type': 'application/json' } });
    } catch (_) {
        // ignore network errors on logout
    }
    clearTokens();
}

async function readErrorMessage(response) {
    try {
        const data = await response.json();
        return data.message || `HTTP ${response.status}: ${response.statusText}`;
    } catch (_) {
        return `HTTP ${response.status}: ${response.statusText}`;
    }
}

async function authFetch(input, init = {}) {
    const headers = new Headers(init.headers || {});
    const token = getAccessToken();
    if (token) headers.set('Authorization', `Bearer ${token}`);
    headers.set('Content-Type', headers.get('Content-Type') || 'application/json');
    let response = await fetch(input, { ...init, headers });
    if (response.status !== 401) return response;
    // try refresh once
    try {
        const newAccess = await refreshToken();
        const retryHeaders = new Headers(init.headers || {});
        retryHeaders.set('Authorization', `Bearer ${newAccess}`);
        if (!retryHeaders.get('Content-Type')) retryHeaders.set('Content-Type', 'application/json');
        response = await fetch(input, { ...init, headers: retryHeaders });
    } catch (_) {
        await logout();
    }
    return response;
}

export default {
    API_URL,
    signin,
    refreshToken,
    logout,
    authFetch,
    readErrorMessage,
    getAccessToken,
    getRefreshToken,
    setTokens,
    clearTokens
};
