import { normalizeSignedLicenseInput } from './token';
import type { AsukaLicenseTokenInput, AsukaSignedLicensePayload } from './license.types';

export interface AsukaLicenseCachePayload {
  signed: AsukaSignedLicensePayload;
  cachedAt: string;
}

function getSafeStorage(): Storage | null {
  try {
    if (typeof localStorage === 'undefined') return null;
    return localStorage;
  } catch {
    return null;
  }
}

export function saveLicenseCache(key: string, signed: AsukaLicenseTokenInput): void {
  const storage = getSafeStorage();
  if (!storage || !key) return;
  try {
    const payload: AsukaLicenseCachePayload = {
      signed: normalizeSignedLicenseInput(signed),
      cachedAt: new Date().toISOString(),
    };
    storage.setItem(key, JSON.stringify(payload));
  } catch {
    // ignore storage errors
  }
}

export function loadLicenseCache(key: string): AsukaLicenseCachePayload | null {
  const storage = getSafeStorage();
  if (!storage || !key) return null;
  try {
    const raw = storage.getItem(key);
    if (!raw) return null;
    const parsed = JSON.parse(raw) as AsukaLicenseCachePayload;
    if (!parsed?.signed) return null;
    return {
      ...parsed,
      signed: normalizeSignedLicenseInput(parsed.signed),
    };
  } catch {
    return null;
  }
}

export function clearLicenseCache(key: string): void {
  const storage = getSafeStorage();
  if (!storage || !key) return;
  try {
    storage.removeItem(key);
  } catch {
    // ignore storage errors
  }
}
