import { RoleFactory } from '../roles/role-factory';

interface TokenCache {
  token: string;
  expiresAt: number;
}

export class RoleAuthManager {
  private static tokenCache: Map<string, TokenCache> = new Map();
  private static readonly API_BASE_URL = process.env.VITE_API_BASE_URL || 'http://localhost:8084';
  private static readonly TOKEN_EXPIRY_BUFFER = 60000;

  static async getRoleToken(roleName: string): Promise<string> {
    const cached = this.tokenCache.get(roleName);
    
    if (cached && cached.expiresAt > Date.now() + this.TOKEN_EXPIRY_BUFFER) {
      return cached.token;
    }

    const role = RoleFactory.getRole(roleName);
    const token = await this.authenticateWithBackend(role.credentials);
    
    this.tokenCache.set(roleName, {
      token,
      expiresAt: Date.now() + 3600000
    });

    return token;
  }

  private static async authenticateWithBackend(credentials: { username: string; password: string }): Promise<string> {
    const path = '/api/auth/login';
    const body = JSON.stringify(credentials);

    const response = await fetch(`${this.API_BASE_URL}${path}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body,
    });

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`Authentication failed for user ${credentials.username}: ${response.statusText} - ${errorText}`);
    }

    const data = await response.json();
    return data.data?.token || data.token;
  }

  static clearCache(): void {
    this.tokenCache.clear();
  }

  static clearRoleToken(roleName: string): void {
    this.tokenCache.delete(roleName);
  }
}
