"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GithubProvider = void 0;
const axios_1 = require("@nestjs/axios");
const common_1 = require("@nestjs/common");
const setting_service_1 = require("../../setting/setting.service");
const abstract_provider_1 = require("./abstract.provider");
let GithubProvider = class GithubProvider extends abstract_provider_1.BaseOAuthProvider {
    constructor(http, setting) {
        super(http);
        this.setting = setting;
    }
    getProviderType() {
        return 'GITHUB';
    }
    async getAuthUrl(callbackPath) {
        const settings = await this.setting.getSettingValues([
            'github_client_id',
            'github_client_secret',
            'github_scopes',
            'api-url',
        ]);
        const fixedCallbackPath = '/oauth/github/callback';
        const redirectURI = new URL(fixedCallbackPath, settings['api-url']).toString();
        const scopes = settings['github_scopes'];
        const type = callbackPath.split('/').pop() || 'login';
        const params = new URLSearchParams({
            client_id: settings['github_client_id'],
            redirect_uri: redirectURI,
            scope: scopes.join(' '),
            allow_signup: 'true',
            state: type,
        });
        return `https://github.com/login/oauth/authorize?${params.toString()}`;
    }
    async getProfile(code) {
        const settings = await this.setting.getSettingValues([
            'github_client_id',
            'github_client_secret',
            'github_scopes',
            'api-url',
        ]);
        const fixedCallbackPath = '/oauth/github/callback';
        const redirectURI = new URL(fixedCallbackPath, settings['api-url'].replace(":3200", ":3100")).toString();
        const tokenResponse = await this.http.axiosRef.post('https://github.com/login/oauth/access_token', {
            client_id: settings['github_client_id'],
            client_secret: settings['github_client_secret'],
            code,
            redirect_uri: redirectURI,
        }, {
            headers: {
                Accept: 'application/json',
            },
        });
        const { access_token, error, error_description } = tokenResponse.data;
        if (error || !access_token) {
            throw new Error(`GitHub OAuth error: ${error_description || error || 'No access token received'}`);
        }
        const profileResponse = await this.http.axiosRef.get('https://api.github.com/user', {
            headers: {
                Authorization: `Bearer ${access_token}`,
            },
        });
        const profile = profileResponse.data;
        let email = profile.email;
        if (!email) {
            const emailResponse = await this.http.axiosRef.get('https://api.github.com/user/emails', {
                headers: {
                    Authorization: `Bearer ${access_token}`,
                },
            });
            const primaryEmail = emailResponse.data.find((e) => e.primary && e.verified);
            email = (primaryEmail === null || primaryEmail === void 0 ? void 0 : primaryEmail.email) || null;
        }
        return {
            id: profile.id.toString(),
            email,
            name: profile.name || profile.login,
            picture: profile.avatar_url,
            oauth_tokens: {
                access_token: access_token,
                refresh_token: access_token,
                expires_in: null,
                token_type: 'bearer',
            },
        };
    }
};
exports.GithubProvider = GithubProvider;
exports.GithubProvider = GithubProvider = __decorate([
    (0, common_1.Injectable)(),
    __param(1, (0, common_1.Inject)((0, common_1.forwardRef)(() => setting_service_1.SettingService))),
    __metadata("design:paramtypes", [axios_1.HttpService,
        setting_service_1.SettingService])
], GithubProvider);
//# sourceMappingURL=github.provider.js.map