'use client';
import { encrypt, decrypt } from './crypto';
const AUTH_STORAGE_KEY = 'brainfish-api-global-auth';
/**
 * Fetch device ID from backend API
 * The device ID is stored in an httpOnly cookie
 * Throws error if device ID cannot be fetched (no fallback)
 */ export async function fetchDeviceId() {
    const response = await fetch('/api/device', {
        credentials: 'include'
    });
    if (!response.ok) {
        throw new Error('Failed to fetch device ID');
    }
    const data = await response.json();
    if (!data.deviceId) {
        throw new Error('No device ID returned from server');
    }
    return data.deviceId;
}
/**
 * Encrypted localStorage wrapper for global authentication
 * Uses device ID from backend as encryption key
 * No fallbacks - encryption is required
 */ export const authStorage = {
    /**
   * Save auth configuration to localStorage (encrypted)
   * Requires valid device ID - throws if missing
   */ async save (auth, deviceId) {
        if (!deviceId) {
            throw new Error('Device ID required for secure storage');
        }
        const data = {
            globalAuth: auth,
            timestamp: Date.now()
        };
        const encrypted = await encrypt(JSON.stringify(data), deviceId);
        localStorage.setItem(AUTH_STORAGE_KEY, encrypted);
    },
    /**
   * Load auth configuration from localStorage (decrypted)
   * Returns null if no data or decryption fails
   */ async load (deviceId) {
        if (!deviceId) return null;
        const stored = localStorage.getItem(AUTH_STORAGE_KEY);
        if (!stored) return null;
        try {
            const jsonData = await decrypt(stored, deviceId);
            const data = JSON.parse(jsonData);
            if (!data.globalAuth?.authType) {
                localStorage.removeItem(AUTH_STORAGE_KEY);
                return null;
            }
            return data.globalAuth;
        } catch  {
            // Decryption failed - clear corrupted/invalid data
            localStorage.removeItem(AUTH_STORAGE_KEY);
            return null;
        }
    },
    /**
   * Clear stored auth configuration
   */ clear () {
        localStorage.removeItem(AUTH_STORAGE_KEY);
    }
};
