// apps/web/lib/auth-token.ts
// Single source of truth for all token operations

const TOKEN_KEY = 'access_token';
const USER_KEY = 'user';

export const tokenUtils = {
  // Get token from any available storage
  get(): string | null {
    if (typeof window === 'undefined') return null;
    
    const token = 
      localStorage.getItem(TOKEN_KEY) ??
      localStorage.getItem('token') ??
      sessionStorage.getItem(TOKEN_KEY) ??
      this.getCookie(TOKEN_KEY) ??
      this.getCookie('token') ??
      null;

    if (token === 'undefined' || token === 'null' || token === '') {
      return null;
    }
    return token;
  },

  // Save token to both localStorage AND cookie
  save(token: string): void {
    if (typeof window === 'undefined') return;
    if (!token || token === 'undefined' || token === 'null') return;
    
    localStorage.setItem(TOKEN_KEY, token);
    document.cookie = `${TOKEN_KEY}=${encodeURIComponent(token)}; path=/; max-age=${30*24*60*60}; SameSite=Lax`;
  },

  // Clear from all storages
  clear(): void {
    if (typeof window === 'undefined') return;
    localStorage.removeItem(TOKEN_KEY);
    localStorage.removeItem('token');
    localStorage.removeItem('refresh_token');
    localStorage.removeItem(USER_KEY);
    localStorage.removeItem('userRole');
    document.cookie = `${TOKEN_KEY}=; path=/; max-age=0; SameSite=Lax`;
    document.cookie = `token=; path=/; max-age=0; SameSite=Lax`;
  },

  // Cookie reader
  getCookie(name: string): string | null {
    if (typeof document === 'undefined') return null;
    const match = document.cookie.match(
      new RegExp('(?:^|; )' + name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '=([^;]*)')
    );
    return match ? decodeURIComponent(match[1]) : null;
  },

  // Save user data
  saveUser(user: any): void {
    if (typeof window === 'undefined') return;
    localStorage.setItem(USER_KEY, JSON.stringify(user));
    if (user?.role) {
      localStorage.setItem('userRole', user.role);
    }
  },

  // Get user data
  getUser(): any | null {
    if (typeof window === 'undefined') return null;
    try {
      return JSON.parse(localStorage.getItem(USER_KEY) ?? 'null');
    } catch { 
      return null; 
    }
  },
};
