// Authentication Service
import { apiClient } from '../api/client';
import type { LoginCredentials, User } from '@/types';

/**
 * Authentication Service
 * 
 * Handles authentication state and token management.
 * Uses sessionStorage for better security (tokens cleared on tab close).
 * 
 * Note: For production, consider using httpOnly cookies set by the backend
 * for maximum security against XSS attacks.
 */
class AuthService {
  private readonly TOKEN_KEY = 'auth_token';
  private readonly USER_KEY = 'user';
  
  // Use sessionStorage instead of localStorage for better security
  // Tokens are cleared when the browser tab/window is closed
  private readonly storage = sessionStorage;

  async login(credentials: LoginCredentials): Promise<{ user: User; token: string }> {
    // TODO: Replace with actual login endpoint when available
    // For now, this is a placeholder that would call the backend
    // const response = await apiClient.post('/api/auth/login', credentials);
    
    // Mock response for development
    const mockUser: User = {
      id: '1',
      employeeId: 'emp-001',
      name: 'Admin User',
      email: credentials.username,
      role: 'DBIS_Super_Admin',
      permissions: ['all'],
    };

    const mockToken = 'mock-jwt-token';

    this.setToken(mockToken);
    this.setUser(mockUser);

    return { user: mockUser, token: mockToken };
  }

  async logout(): Promise<void> {
    try {
      // Call logout endpoint if available
      // await apiClient.post('/api/auth/logout');
    } catch (error) {
      // Ignore errors on logout
    } finally {
      this.clearAuth();
    }
  }

  getToken(): string | null {
    try {
      return this.storage.getItem(this.TOKEN_KEY);
    } catch (error) {
      // Handle storage access errors (e.g., private browsing mode)
      console.error('Failed to get token from storage:', error);
      return null;
    }
  }

  getUser(): User | null {
    try {
      const userStr = this.storage.getItem(this.USER_KEY);
      return userStr ? JSON.parse(userStr) : null;
    } catch (error) {
      console.error('Failed to get user from storage:', error);
      return null;
    }
  }

  setToken(token: string): void {
    try {
      this.storage.setItem(this.TOKEN_KEY, token);
    } catch (error) {
      console.error('Failed to set token in storage:', error);
      throw new Error('Failed to save authentication token');
    }
  }

  setUser(user: User): void {
    try {
      this.storage.setItem(this.USER_KEY, JSON.stringify(user));
    } catch (error) {
      console.error('Failed to set user in storage:', error);
      throw new Error('Failed to save user data');
    }
  }

  clearAuth(): void {
    try {
      this.storage.removeItem(this.TOKEN_KEY);
      this.storage.removeItem(this.USER_KEY);
    } catch (error) {
      console.error('Failed to clear auth from storage:', error);
    }
  }

  isAuthenticated(): boolean {
    const token = this.getToken();
    if (!token) return false;

    // Check if token is expired (basic check)
    try {
      const payload = JSON.parse(atob(token.split('.')[1]));
      const exp = payload.exp * 1000; // Convert to milliseconds
      return Date.now() < exp;
    } catch {
      return false;
    }
  }

  async refreshToken(): Promise<string | null> {
    try {
      // TODO: Implement token refresh
      // const response = await apiClient.post('/api/auth/refresh');
      // this.setToken(response.token);
      // return response.token;
      return this.getToken();
    } catch (error) {
      this.clearAuth();
      return null;
    }
  }
}

export const authService = new AuthService();

