"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.oauthLogin = oauthLogin;
exports.oauthLogout = oauthLogout;
exports.oauthCallback = oauthCallback;
const oauth_1 = require("../components/oauth");
function oauthLogin(req, res) {
    res.redirect((0, oauth_1.getOAuthLoginPath)(req, res));
}
function oauthLogout(_, res) {
    (0, oauth_1.removeOAuthCookies)(res);
    res.redirect('/');
}
async function oauthCallback(req, res) {
    const { code, state } = req.query;
    if (!code) {
        throw new Error('Authorization code is not specified');
    }
    let redirectURL = '/';
    if (state) {
        redirectURL = req.cookies[state]?.retPath ?? '/';
    }
    try {
        const tokens = await (0, oauth_1.exchangeOAuthToken)(req, code);
        (0, oauth_1.saveOAuthTokensInCookies)(res, tokens);
        res.redirect(redirectURL);
    }
    catch (e) {
        req.ctx.logError('exchange token error', e);
        const message = e instanceof Error ? e.message : 'Unknown error';
        res.status(500).send(message);
    }
}
