import { socialConfig } from '../../../config/social.config';
import { SocialProfile } from '../social.service';

/**
 * EN: Facebook OAuth Provider
 * VI: Provider OAuth của Facebook
 */

export class FacebookProvider {
  private readonly appId = socialConfig.facebook.appId;
  private readonly appSecret = socialConfig.facebook.appSecret;
  private readonly redirectUri = socialConfig.facebook.redirectUri;

  /**
   * EN: Get authorization URL
   * VI: Lấy URL xác thực
   */
  getAuthorizationUrl(state?: string): string {
    const params = new URLSearchParams({
      client_id: this.appId!,
      redirect_uri: this.redirectUri,
      scope: 'email public_profile',
      response_type: 'code',
      ...(state && { state }),
    });

    return `https://www.facebook.com/v18.0/dialog/oauth?${params.toString()}`;
  }

  /**
   * EN: Get user profile from authorization code
   * VI: Lấy profile người dùng từ authorization code
   */
  async getProfile(code: string, redirectUri?: string): Promise<SocialProfile> {
    // Exchange code for access token
    const tokenUrl = new URL('https://graph.facebook.com/v18.0/oauth/access_token');
    tokenUrl.searchParams.set('client_id', this.appId!);
    tokenUrl.searchParams.set('client_secret', this.appSecret!);
    tokenUrl.searchParams.set('redirect_uri', redirectUri || this.redirectUri);
    tokenUrl.searchParams.set('code', code);

    const tokenRes = await fetch(tokenUrl.toString());

    if (!tokenRes.ok) {
      throw new Error('Failed to exchange code for token');
    }

    const tokenData = await tokenRes.json();
    const accessToken = tokenData.access_token;

    // Get user info
    const userUrl = new URL('https://graph.facebook.com/v18.0/me');
    userUrl.searchParams.set('fields', 'id,name,email,picture');
    userUrl.searchParams.set('access_token', accessToken);

    const userResponse = await fetch(userUrl.toString());

    if (!userResponse.ok) {
      throw new Error('Failed to get user info');
    }

    const userData = await userResponse.json();

    return {
      id: userData.id,
      email: userData.email || `${userData.id}@facebook.com`,
      name: userData.name,
      avatar: userData.picture?.data?.url,
      username: userData.name?.toLowerCase().replace(/\s+/g, '_'),
    };
  }
}
