import { requestJson } from './apiClient';

const SUPER_TOKEN_KEY = 'super_token';

export function getSuperAuthToken() {
    return localStorage.getItem(SUPER_TOKEN_KEY) || '';
}

export function setSuperAuthToken(token) {
    const normalized = String(token || '').trim();
    if (!normalized) {
        localStorage.removeItem(SUPER_TOKEN_KEY);
        return;
    }
    localStorage.setItem(SUPER_TOKEN_KEY, normalized);
}

export function clearSuperAuthToken() {
    localStorage.removeItem(SUPER_TOKEN_KEY);
}

export function hasSuperAuthToken() {
    return Boolean(getSuperAuthToken());
}

export async function superLogin({ username, password }) {
    const data = await requestJson('/super/v1/auth/login', {
        method: 'POST',
        body: { username, password }
    });
    const token = data?.token ?? '';
    setSuperAuthToken(token);
    return token;
}

export async function refreshSuperToken() {
    const data = await requestJson('/super/v1/auth/token');
    const token = data?.token ?? '';
    if (token) setSuperAuthToken(token);
    return token;
}
