"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);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GitHubAuthProvider = void 0;
const base_auth_provider_1 = require("./base-auth.provider");
const common_1 = require("@nestjs/common");
const typeorm_1 = 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");
let GitHubAuthProvider = class GitHubAuthProvider extends base_auth_provider_1.BaseAuthProvider {
    dataSource;
    providerName = auth_constants_1.GITHUB_AUTH_PROVIDER;
    githubConfig;
    constructor(dataSource) {
        const userRepository = dataSource.getRepository(user_entity_1.NestAuthUser);
        const authIdentityRepository = dataSource.getRepository(identity_entity_1.NestAuthIdentity);
        super(userRepository, authIdentityRepository);
        this.dataSource = dataSource;
        this.githubConfig = this.options.github;
        this.enabled = Boolean(this.githubConfig);
    }
    async validate(credentials) {
        try {
            const userResponse = await fetch('https://api.github.com/user', {
                headers: {
                    Authorization: `Bearer ${credentials.accessToken}`,
                    Accept: 'application/vnd.github.v3+json',
                },
            });
            if (!userResponse.ok) {
                throw new common_1.UnauthorizedException('Invalid GitHub token');
            }
            const userData = await userResponse.json();
            let email = userData.email;
            if (!email) {
                const emailsResponse = await fetch('https://api.github.com/user/emails', {
                    headers: {
                        Authorization: `Bearer ${credentials.accessToken}`,
                        Accept: 'application/vnd.github.v3+json',
                    },
                });
                if (emailsResponse.ok) {
                    const emails = await emailsResponse.json();
                    const primaryEmail = emails.find((e) => e.primary) || emails[0];
                    email = primaryEmail?.email || '';
                }
            }
            return {
                userId: userData.id.toString(),
                email: email || '',
                metadata: {
                    name: userData.name || userData.login,
                    login: userData.login,
                    avatar: userData.avatar_url,
                    bio: userData.bio,
                    company: userData.company,
                    location: userData.location,
                },
            };
        }
        catch (error) {
            throw new common_1.UnauthorizedException('Invalid GitHub token');
        }
    }
    getRequiredFields() {
        return ['accessToken'];
    }
};
exports.GitHubAuthProvider = GitHubAuthProvider;
exports.GitHubAuthProvider = GitHubAuthProvider = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [typeorm_1.DataSource])
], GitHubAuthProvider);
//# sourceMappingURL=github-auth.provider.js.map