export interface TokenPair {
  accessToken: string;
  refreshToken: string;
  accessTokenExpiresAt: string;
  refreshTokenExpiresAt: string;
}

const storageKey = 'tiku.platform-admin.tokens';
let currentTokens: TokenPair | null = readTokens();

function readTokens(): TokenPair | null {
  try {
    const raw = localStorage.getItem(storageKey);
    return raw ? (JSON.parse(raw) as TokenPair) : null;
  } catch {
    return null;
  }
}

export const tokenStore = {
  get: () => currentTokens,
  set(tokens: TokenPair | null) {
    currentTokens = tokens;
    if (tokens) localStorage.setItem(storageKey, JSON.stringify(tokens));
    else localStorage.removeItem(storageKey);
    window.dispatchEvent(new CustomEvent('platform-auth-change'));
  },
};
