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

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

export class GitHubProvider {
  private readonly clientId = socialConfig.github.clientId;
  private readonly clientSecret = socialConfig.github.clientSecret;
  private readonly redirectUri = socialConfig.github.redirectUri;

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

    return `https://github.com/login/oauth/authorize?${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 tokenResponse = await fetch('https://github.com/login/oauth/access_token', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json',
      },
      body: JSON.stringify({
        client_id: this.clientId,
        client_secret: this.clientSecret,
        code,
        redirect_uri: redirectUri || this.redirectUri,
      }),
    });

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

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

    // Get user info
    const userResponse = await fetch('https://api.github.com/user', {
      headers: {
        Authorization: `Bearer ${accessToken}`,
        Accept: 'application/vnd.github.v3+json',
      },
    });

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

    const userData = await userResponse.json();

    // Get user email (may be private)
    let email = userData.email;
    if (!email) {
      const emailResponse = await fetch('https://api.github.com/user/emails', {
        headers: {
          Authorization: `Bearer ${accessToken}`,
          Accept: 'application/vnd.github.v3+json',
        },
      });

      if (emailResponse.ok) {
        const emails = await emailResponse.json();
        const primaryEmail = emails.find((e: any) => e.primary);
        email = primaryEmail?.email || emails[0]?.email || `${userData.id}@github.com`;
      }
    }

    return {
      id: userData.id.toString(),
      email: email || `${userData.id}@github.com`,
      name: userData.name || userData.login,
      avatar: userData.avatar_url,
      username: userData.login,
    };
  }
}
