"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.GoogleProvider = 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 GoogleProvider = class GoogleProvider extends abstract_provider_1.BaseOAuthProvider {
    constructor(http, setting) {
        super(http);
        this.setting = setting;
    }
    getProviderType() {
        return 'GOOGLE';
    }
    async getAuthUrl(callbackPath) {
        var _a;
        const settings = await this.setting.getSettingValues([
            'google_client_id',
            'google_client_secret',
            'google_scopes',
            'url',
        ]);
        const redirectURI = new URL(callbackPath, settings['url']).toString();
        const params = new URLSearchParams({
            client_id: settings['google_client_id'],
            redirect_uri: redirectURI,
            response_type: 'code',
            scope: ((_a = settings['google_scopes']) !== null && _a !== void 0 ? _a : []).join(' '),
            access_type: 'offline',
            prompt: 'consent',
        });
        return `https://accounts.google.com/o/oauth2/v2/auth?${params}`;
    }
    async getProfile(code, type) {
        const settings = await this.setting.getSettingValues([
            'google_client_id',
            'google_client_secret',
            'google_scopes',
            'url',
        ]);
        const token = await this.fetchToken({
            code,
            url: 'https://oauth2.googleapis.com/token',
            clientId: settings['google_client_id'],
            clientSecret: settings['google_client_secret'],
            redirectUri: `${settings['url']}/callback/google/${type}`,
        });
        const basicProfile = await this.fetchProfile(token.access_token, 'https://www.googleapis.com/oauth2/v2/userinfo');
        const peopleProfile = await this.getGoogleProfileFromAccessToken(token.access_token);
        return Object.assign(Object.assign({}, basicProfile), { gender: peopleProfile.gender, birthday: peopleProfile.birthday, oauth_tokens: {
                access_token: token.access_token,
                refresh_token: token.refresh_token,
                expires_in: token.expires_in,
                token_type: token.token_type,
            } });
    }
    async getGoogleProfileFromAccessToken(accessToken) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
        const url = 'https://people.googleapis.com/v1/people/me?personFields=genders,birthdays';
        const res = await fetch(url, {
            headers: {
                Authorization: `Bearer ${accessToken}`,
            },
        });
        if (!res.ok) {
            throw new Error(`Google People API error: ${res.statusText}`);
        }
        const data = await res.json();
        const gender = (_f = (_c = (_b = (_a = data.genders) === null || _a === void 0 ? void 0 : _a.find((g) => { var _a; return (_a = g.metadata) === null || _a === void 0 ? void 0 : _a.primary; })) === null || _b === void 0 ? void 0 : _b.value) !== null && _c !== void 0 ? _c : (_e = (_d = data.genders) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e.value) !== null && _f !== void 0 ? _f : null;
        const b = (_h = (_g = data.birthdays) === null || _g === void 0 ? void 0 : _g.find((x) => { var _a; return (_a = x.metadata) === null || _a === void 0 ? void 0 : _a.primary; })) !== null && _h !== void 0 ? _h : (_j = data.birthdays) === null || _j === void 0 ? void 0 : _j[0];
        const date = (b === null || b === void 0 ? void 0 : b.date)
            ? { day: b.date.day, month: b.date.month, year: (_k = b.date.year) !== null && _k !== void 0 ? _k : null }
            : null;
        return { gender, birthday: date, raw: data };
    }
};
exports.GoogleProvider = GoogleProvider;
exports.GoogleProvider = GoogleProvider = __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])
], GoogleProvider);
//# sourceMappingURL=google.provider.js.map