"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.FacebookProvider = 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 FacebookProvider = class FacebookProvider extends abstract_provider_1.BaseOAuthProvider {
    constructor(http, setting, prisma) {
        super(http);
        this.setting = setting;
        this.prisma = prisma;
    }
    getProviderType() {
        return 'FACEBOOK';
    }
    async loadConfig() {
        var _a;
        const settings = await this.setting.getSettingValues([
            'oauth-facebook-profile-id',
            'url',
        ]);
        const profileId = Number(settings['oauth-facebook-profile-id']);
        if (!profileId)
            throw new common_1.BadRequestException('Facebook 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('Facebook OAuth profile not found.');
        const { clientId, clientSecret } = (0, integration_profile_utils_1.buildOAuthConfigFromIntegration)(profile.integration_provider.slug, profile.config);
        return { clientId, clientSecret, baseUrl: String((_a = settings['url']) !== null && _a !== void 0 ? _a : '') };
    }
    async getAuthUrl(callbackPath) {
        var _a;
        const { clientId, baseUrl } = await this.loadConfig();
        const settings = await this.setting.getSettingValues(['oauth-facebook-scopes']);
        const scopes = (_a = settings['oauth-facebook-scopes']) !== null && _a !== void 0 ? _a : ['email'];
        const redirectURI = new URL(callbackPath, baseUrl).toString();
        const params = new URLSearchParams({
            client_id: clientId,
            redirect_uri: redirectURI,
            response_type: 'code',
            scope: scopes.join(','),
            auth_type: 'rerequest',
        });
        return `https://www.facebook.com/v17.0/dialog/oauth?${params}`;
    }
    async getProfile(code, type, redirectUri) {
        const { clientId, clientSecret, baseUrl } = await this.loadConfig();
        const resolvedRedirectUri = (redirectUri === null || redirectUri === void 0 ? void 0 : redirectUri.trim()) || `${baseUrl}/oauth/facebook/callback/${type}`;
        const token = await this.fetchToken({
            code,
            url: 'https://graph.facebook.com/v17.0/oauth/access_token',
            clientId,
            clientSecret,
            redirectUri: resolvedRedirectUri,
        });
        const profile = await this.fetchProfile(token.access_token, 'https://graph.facebook.com/me?fields=id,name,email,gender,birthday,picture');
        return Object.assign(Object.assign({}, profile), { oauth_tokens: {
                access_token: token.access_token,
                refresh_token: token.refresh_token,
                expires_in: token.expires_in,
                token_type: token.token_type,
            } });
    }
};
exports.FacebookProvider = FacebookProvider;
exports.FacebookProvider = FacebookProvider = __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])
], FacebookProvider);
//# sourceMappingURL=facebook.provider.js.map