"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.GitHubAuthProvider = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const auth_constants_1 = require("../../auth.constants");
const user_entity_1 = require("../../user/entities/user.entity");
const identity_entity_1 = require("../../user/entities/identity.entity");
const base_auth_provider_1 = require("./base-auth.provider");
let GitHubAuthProvider = class GitHubAuthProvider extends base_auth_provider_1.BaseAuthProvider {
    userRepository;
    authIdentityRepository;
    providerName = auth_constants_1.GITHUB_AUTH_PROVIDER;
    githubConfig;
    constructor(userRepository, authIdentityRepository) {
        super(userRepository, authIdentityRepository);
        this.userRepository = userRepository;
        this.authIdentityRepository = authIdentityRepository;
        this.githubConfig = this.options.github;
        this.enabled = Boolean(this.githubConfig);
    }
    get userApiUrl() {
        return this.githubConfig?.userApiUrl || 'https://api.github.com/user';
    }
    get emailsApiUrl() {
        return this.githubConfig?.emailsApiUrl || 'https://api.github.com/user/emails';
    }
    async validate(credentials, _tenantId) {
        let userResponse;
        try {
            userResponse = await fetch(this.userApiUrl, {
                headers: {
                    Authorization: `Bearer ${credentials.token}`,
                    Accept: 'application/vnd.github.v3+json',
                },
            });
        }
        catch (error) {
            throw new common_1.UnauthorizedException({
                code: 'OAUTH_PROVIDER_ERROR',
                message: 'Could not reach GitHub. Try again in a moment.',
            });
        }
        if (userResponse.status === 401 || userResponse.status === 403) {
            throw new common_1.UnauthorizedException({
                code: 'INVALID_CREDENTIALS',
                message: 'Invalid GitHub token.',
            });
        }
        if (!userResponse.ok) {
            throw new common_1.UnauthorizedException({
                code: 'OAUTH_PROVIDER_ERROR',
                message: 'GitHub returned an unexpected response.',
            });
        }
        let userData;
        try {
            userData = await userResponse.json();
        }
        catch (error) {
            throw new common_1.UnauthorizedException({
                code: 'OAUTH_PROVIDER_ERROR',
                message: 'GitHub returned a malformed response.',
            });
        }
        let email = userData.email;
        let emailVerified = false;
        if (!email) {
            try {
                const emailsResponse = await fetch(this.emailsApiUrl, {
                    headers: {
                        Authorization: `Bearer ${credentials.token}`,
                        Accept: 'application/vnd.github.v3+json',
                    },
                });
                if (emailsResponse.ok) {
                    const emails = await emailsResponse.json();
                    const chosen = emails.find((e) => e.primary && e.verified) ||
                        emails.find((e) => e.verified) ||
                        emails.find((e) => e.primary) ||
                        emails[0];
                    email = chosen?.email || '';
                    emailVerified = chosen?.verified === true;
                }
            }
            catch (error) {
            }
        }
        else {
            emailVerified = true;
        }
        if (!email) {
            throw new common_1.UnauthorizedException({
                code: 'OAUTH_EMAIL_NOT_PUBLIC',
                message: 'Your GitHub email is not publicly visible. ' +
                    'Either make your primary email public on GitHub, grant the user:email scope, ' +
                    'or sign in with a different method.',
            });
        }
        return {
            userId: userData.id.toString(),
            email,
            emailVerified,
            metadata: {
                name: userData.name || userData.login,
                login: userData.login,
                avatar: userData.avatar_url,
                bio: userData.bio,
                company: userData.company,
                location: userData.location,
            },
        };
    }
    getRequiredFields() {
        return ['token'];
    }
};
exports.GitHubAuthProvider = GitHubAuthProvider;
exports.GitHubAuthProvider = GitHubAuthProvider = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectRepository)(user_entity_1.NestAuthUser)),
    __param(1, (0, typeorm_1.InjectRepository)(identity_entity_1.NestAuthIdentity)),
    __metadata("design:paramtypes", [typeorm_2.Repository,
        typeorm_2.Repository])
], GitHubAuthProvider);
//# sourceMappingURL=github-auth.provider.js.map