"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 api_prisma_1 = require("@hed-hog/api-prisma");
const axios_1 = require("@nestjs/axios");
const common_1 = require("@nestjs/common");
const integration_profile_utils_1 = require("../../integration-profile/integration-profile.utils");
const setting_service_1 = require("../../setting/setting.service");
const abstract_provider_1 = require("./abstract.provider");
let GithubProvider = class GithubProvider extends abstract_provider_1.BaseOAuthProvider {
    isAbsoluteCallbackPath(value) {
        return /^[a-z][a-z\d+.-]*:/i.test(String(value || '').trim());
    }
    constructor(http, setting, prisma) {
        super(http);
        this.setting = setting;
        this.prisma = prisma;
    }
    getProviderType() {
        return 'GITHUB';
    }
    async loadConfig() {
        var _a;
        const settings = await this.setting.getSettingValues([
            'oauth-github-profile-id',
            'api-url',
        ]);
        const profileId = Number(settings['oauth-github-profile-id']);
        if (!profileId)
            throw new common_1.BadRequestException('GitHub OAuth profile not configured.');
        const profile = await this.prisma.integration_profile.findUnique({
            where: { id: profileId },
            include: { integration_provider: { select: { slug: true } } },
        });
        if (!profile)
            throw new common_1.BadRequestException('GitHub OAuth profile not found.');
        const { clientId, clientSecret } = (0, integration_profile_utils_1.buildOAuthConfigFromIntegration)(profile.integration_provider.slug, profile.config);
        return { clientId, clientSecret, apiUrl: String((_a = settings['api-url']) !== null && _a !== void 0 ? _a : '') };
    }
    async getAuthUrl(callbackPath) {
        var _a;
        const { clientId, apiUrl } = await this.loadConfig();
        const settings = await this.setting.getSettingValues(['oauth-github-scopes']);
        const scopes = (_a = settings['oauth-github-scopes']) !== null && _a !== void 0 ? _a : ['read:user', 'user:email'];
        const fixedCallbackPath = '/oauth/github/callback';
        const redirectURI = this.isAbsoluteCallbackPath(callbackPath)
            ? callbackPath
            : new URL(fixedCallbackPath, apiUrl).toString();
        const type = this.isAbsoluteCallbackPath(callbackPath)
            ? 'login'
            : callbackPath.split('/').pop() || 'login';
        const params = new URLSearchParams({
            client_id: clientId,
            redirect_uri: redirectURI,
            scope: scopes.join(' '),
            allow_signup: 'true',
            state: type,
        });
        return `https://github.com/login/oauth/authorize?${params.toString()}`;
    }
    async getProfile(code, _type, redirectUri) {
        const { clientId, clientSecret, apiUrl } = await this.loadConfig();
        const fixedCallbackPath = '/oauth/github/callback';
        const redirectURI = (redirectUri === null || redirectUri === void 0 ? void 0 : redirectUri.trim())
            ? redirectUri.trim()
            : new URL(fixedCallbackPath, apiUrl.replace(':3200', ':3100')).toString();
        const tokenResponse = await this.http.axiosRef.post('https://github.com/login/oauth/access_token', {
            client_id: clientId,
            client_secret: clientSecret,
            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,
        api_prisma_1.PrismaService])
], GithubProvider);
//# sourceMappingURL=github.provider.js.map