const axios = require('axios');

/**
 * User Authentication Client for Unified Tech Stack Service
 * Handles communication with the user-auth service for user validation
 */
class UserAuthClient {
  constructor() {
    this.baseURL = process.env.USER_AUTH_URL || 'http://localhost:8011';
    this.timeout = 10000; // 10 seconds
  }

  /**
   * Validate user token and get user information
   */
  async validateUserToken(token) {
    try {
      const response = await axios.get(`${this.baseURL}/api/auth/me`, {
        timeout: this.timeout,
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });

      return {
        success: true,
        data: response.data,
        user: response.data.data.user
      };

    } catch (error) {
      console.error('❌ User token validation error:', error.message);
      return {
        success: false,
        error: error.response?.data?.message || error.message,
        status: error.response?.status || 500
      };
    }
  }

  /**
   * Get user by ID
   */
  async getUserById(userId) {
    try {
      const response = await axios.get(`${this.baseURL}/api/auth/user/${userId}`, {
        timeout: this.timeout,
        headers: {
          'Content-Type': 'application/json'
        }
      });

      return {
        success: true,
        data: response.data,
        user: response.data.data
      };

    } catch (error) {
      console.error('❌ Get user by ID error:', error.message);
      return {
        success: false,
        error: error.response?.data?.message || error.message,
        status: error.response?.status || 500
      };
    }
  }

  /**
   * Check if user exists and is active
   */
  async checkUserExists(userId) {
    try {
      const result = await this.getUserById(userId);
      return {
        success: result.success,
        exists: result.success && result.user?.is_active === true,
        user: result.user
      };
    } catch (error) {
      console.error('❌ Check user exists error:', error.message);
      return {
        success: false,
        exists: false,
        error: error.message
      };
    }
  }

  /**
   * Check service health
   */
  async checkHealth() {
    try {
      const response = await axios.get(`${this.baseURL}/health`, {
        timeout: 5000,
        headers: {
          'Content-Type': 'application/json'
        }
      });

      return {
        success: true,
        status: 'healthy',
        responseTime: response.headers['x-response-time'] || 'unknown',
        data: response.data
      };

    } catch (error) {
      console.error('❌ User Auth health check error:', error.message);
      return {
        success: false,
        status: 'unhealthy',
        error: error.message
      };
    }
  }
}

module.exports = UserAuthClient;
