"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createGoogleOAuthRoutes = createGoogleOAuthRoutes;
const express_1 = require("express");
const plugin_config_1 = require("../../../backend/src/core/plugin-config");
const auth_1 = require("../../../backend/src/middleware/auth");
function createGoogleOAuthRoutes(ctx) {
    const router = (0, express_1.Router)();
    const { db } = ctx;
    const storedConfig = plugin_config_1.pluginConfig.get('google-oauth') || {};
    const GOOGLE_CLIENT_ID = storedConfig.clientId || process.env.GOOGLE_CLIENT_ID;
    const GOOGLE_CLIENT_SECRET = storedConfig.clientSecret || process.env.GOOGLE_CLIENT_SECRET;
    const GOOGLE_CALLBACK = storedConfig.callbackUrl || process.env.GOOGLE_CALLBACK_URL || '/api/auth/google/callback';
    const rawBasePath = storedConfig.basePath || process.env.NEXT_PUBLIC_BASE_PATH || process.env.NEXT_BASE_PATH || '';
    const basePath = rawBasePath ? `/${String(rawBasePath).replace(/^\/+|\/+$/g, '')}` : '';
    // GET / — Redirect to Google
    router.get('/', (_req, res) => {
        if (!GOOGLE_CLIENT_ID)
            return res.status(503).json({ error: 'Google OAuth não configurado' });
        const url = `https://accounts.google.com/o/oauth2/v2/auth?` +
            `client_id=${GOOGLE_CLIENT_ID}&redirect_uri=${encodeURIComponent(GOOGLE_CALLBACK)}` +
            `&response_type=code&scope=openid%20email%20profile&access_type=offline`;
        res.redirect(url);
    });
    // GET /callback — Handle Google callback
    router.get('/callback', async (req, res) => {
        try {
            const { code } = req.query;
            if (!code || !GOOGLE_CLIENT_ID || !GOOGLE_CLIENT_SECRET) {
                return res.status(400).json({ error: 'Código ou config ausente' });
            }
            // Exchange code for token
            const tokenRes = await fetch('https://oauth2.googleapis.com/token', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    code, client_id: GOOGLE_CLIENT_ID, client_secret: GOOGLE_CLIENT_SECRET,
                    redirect_uri: GOOGLE_CALLBACK, grant_type: 'authorization_code',
                }),
            });
            const tokenData = await tokenRes.json();
            if (!tokenRes.ok || !(tokenData === null || tokenData === void 0 ? void 0 : tokenData.access_token)) {
                ctx.logger.error(`Google OAuth token error: ${JSON.stringify(tokenData)}`);
                return res.status(400).json({ error: 'Falha ao obter token do Google' });
            }
            // Get user info
            const userRes = await fetch('https://www.googleapis.com/oauth2/v2/userinfo', {
                headers: { Authorization: `Bearer ${tokenData.access_token}` },
            });
            const googleUser = await userRes.json();
            if (!userRes.ok || !(googleUser === null || googleUser === void 0 ? void 0 : googleUser.email)) {
                ctx.logger.error(`Google OAuth userinfo error: ${JSON.stringify(googleUser)}`);
                return res.status(400).json({ error: 'Falha ao obter e-mail do Google' });
            }
            // Find or create user
            let user = await db('users').where({ email: googleUser.email }).first();
            if (!user) {
                const [id] = await db('users').insert({
                    name: googleUser.name, email: googleUser.email,
                    role: 'user', status: 'active', google_id: googleUser.id,
                    created_at: new Date(),
                    updated_at: new Date(),
                });
                user = { id, name: googleUser.name, email: googleUser.email, role: 'user' };
            }
            else if (!user.google_id) {
                await db('users').where({ id: user.id }).update({ google_id: googleUser.id, updated_at: new Date() });
            }
            if (user.deleted_at || user.status === 'banned') {
                return res.status(401).json({ error: 'Conta desativada' });
            }
            const tokens = (0, auth_1.generateTokens)(user);
            await ctx.hooks.emit('user:google_login', { userId: user.id, email: user.email });
            // Redirect to frontend with token
            res.redirect(`${basePath}/login?token=${encodeURIComponent(tokens.accessToken)}&google=1`);
        }
        catch (err) {
            ctx.logger.error(`Google OAuth error: ${err.message}`);
            res.status(500).json({ error: 'Erro no OAuth' });
        }
    });
    return router;
}
//# sourceMappingURL=routes.js.map
