// API URL - extract base from GraphQL endpoint
const API_URL = (import.meta.env.VITE_GRAPHQL_ENDPOINT || 'http://localhost:5000/graphql').replace('/graphql', '');

export interface UserContext {
  id: string | null;
  email: string | null;
  name: string | null;
  companyId: string | null;
  isApiKey: boolean;
}

class AuthService {
  private userContext: UserContext | null = null;

  /**
   * Fetch user profile from the backend
   * Returns null if not authenticated
   */
  async refreshUserContext(): Promise<UserContext | null> {
    try {
      const response = await fetch(`${API_URL}/api/profile`, {
        credentials: 'include',
      });

      if (response.ok) {
        this.userContext = await response.json();
        return this.userContext;
      }

      // 401/403 means not authenticated
      this.userContext = null;
      return null;
    } catch (error) {
      console.error('Failed to fetch user profile:', error);
      this.userContext = null;
      return null;
    }
  }

  /**
   * Redirect to login page
   * The backend will handle OIDC authentication and redirect back
   */
  login(returnUrl?: string): void {
    const url = returnUrl || window.location.href;
    window.location.href = `${API_URL}/api/login?returnUrl=${encodeURIComponent(url)}`;
  }

  /**
   * Logout and clear session
   */
  async logout(): Promise<void> {
    try {
      await fetch(`${API_URL}/api/logout`, {
        method: 'GET',
        credentials: 'include',
      });
    } catch (error) {
      console.error('Logout error:', error);
    }

    this.userContext = null;
    window.location.reload();
  }

  /**
   * Get the current user context
   */
  get user(): UserContext | null {
    return this.userContext;
  }

  /**
   * Check if user is authenticated
   */
  get isAuthenticated(): boolean {
    return this.userContext !== null;
  }
}

// Singleton instance
export const authService = new AuthService();
