import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { socialLoginConstant } from 'src/constants/auth';
import { catchError, lastValueFrom, map, of } from 'rxjs';

/**
 * FacebookService - Service for Facebook OAuth token validation
 *
 * This service handles verification of Facebook access tokens by making
 * an API call to Facebook's token debug endpoint. It validates that tokens
 * are genuine, not expired, and retrieves basic user information.
 *
 * Facebook token verification flow:
 * 1. Client obtains Facebook access token via OAuth
 * 2. Server sends token to Facebook for validation
 * 3. Facebook returns token metadata and user information
 * 4. Server processes validated user data
 *
 * @see https://developers.facebook.com/docs/facebook-login/access-tokens/#debug
 *
 * @example
 * // Verify a Facebook access token
 * const facebookData = await facebookService.tokenVerify(facebookAccessToken);
 * // Returns Facebook API response with user data
 */
@Injectable()
export class FacebookService {
  constructor(private readonly httpService: HttpService) {}

  /**
   * Validates a Facebook access token via Facebook's debug endpoint
   *
   * Makes an HTTP GET request to Facebook's token debug endpoint to:
   * - Verify token validity and expiration
   * - Retrieve app ID and user ID
   * - Get scopes/permissions granted
   * - Check if token was issued to your app
   *
   * @param token - Facebook OAuth access token to validate
   * @returns Promise resolving to Facebook API response data
   * @throws Error if the HTTP request fails or returns invalid data
   *
   * @note Uses RxJS observables converted to Promise with lastValueFrom
   * @note Includes error handling to catch HTTP request failures
   *
   * @example
   * const result = await this.facebookService.tokenVerify('facebook_access_token');
   * // Result contains: { data: { app_id, user_id, is_valid, scopes, ... } }
   */
  tokenVerify(token: string) {
    // Construct the Facebook debug token endpoint URL
    const facebookDebugUrl = `${socialLoginConstant.facebook_url}${token}`;

    // Make HTTP request to Facebook and process response
    return lastValueFrom(
      this.httpService.get(facebookDebugUrl).pipe(
        // Extract data from HTTP response
        map((response) => response.data),

        // Handle errors gracefully
        catchError((error) => {
          // Convert error to user-friendly message
          // Consider logging the actual error for debugging
          console.error('Facebook token verification failed:', error);

          // Return error message (consider throwing instead for better error handling)
          return of(`Alert: ${error.message}`);
        }),
      ),
    );
  }
}
