"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = createAuthRouter;
const express_1 = require("express");
const authManager_1 = require("../auth/authManager");
const isDevelopment = process.env.NODE_ENV === 'development';
const ACCOUNT_SERVER_URL = isDevelopment ? 'http://localhost:2999' : 'https://repoburg.com/api/account';
console.log(`Running in ${isDevelopment ? 'development' : 'production'} mode`);
console.log(`Using ACCOUNT_SERVER_URL: ${ACCOUNT_SERVER_URL}`);
function createAuthRouter(wss) {
    const router = (0, express_1.Router)();
    router.get('/status', async (req, res) => {
        const status = await authManager_1.authManager.getAuthStatus();
        res.json({ status });
    });
    router.post('/initiate', async (req, res) => {
        try {
            const response = await fetch(`${ACCOUNT_SERVER_URL}/device/initiate`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' }
            });
            if (!response.ok) {
                throw new Error(`Failed to initiate device auth: ${response.statusText}`);
            }
            const { device_code, loginUrl } = await response.json();
            // Start polling in the background
            pollForToken(device_code, wss);
            res.json({ loginUrl });
        }
        catch (error) {
            console.error('Error initiating device auth flow:', error);
            res.status(500).json({ error: 'Could not start authentication flow.' });
        }
    });
    router.post('/logout', async (req, res) => {
        try {
            await authManager_1.authManager.logout();
            res.status(200).json({ message: 'Successfully logged out.' });
        }
        catch (error) {
            console.error('Error during logout:', error);
            res.status(500).json({ error: 'Could not log out.' });
        }
    });
    return router;
}
async function pollForToken(deviceCode, wss) {
    const pollInterval = 5000; // 5 seconds
    const maxAttempts = 120; // 10 minutes
    let attempts = 0;
    console.log(`Polling for token with device code: ${deviceCode}`);
    const intervalId = setInterval(async () => {
        if (attempts >= maxAttempts) {
            clearInterval(intervalId);
            console.log(`Polling stopped for ${deviceCode} after reaching max attempts.`);
            return;
        }
        attempts++;
        try {
            // account-server expects 'code' query param, not 'device_code'
            const response = await fetch(`${ACCOUNT_SERVER_URL}/device/poll?code=${deviceCode}`);
            if (response.status === 410) { // Gone (expired)
                console.log(`Device code ${deviceCode} has expired.`);
                clearInterval(intervalId);
                return;
            }
            if (!response.ok) {
                // Continue polling on other errors
                console.warn(`Polling failed with status: ${response.status}`);
                return;
            }
            const data = await response.json();
            // account-server returns { status: 'authorized', access_token: '...' }
            if (data.status === 'authorized' && data.access_token) {
                console.log(`Successfully retrieved access token for ${deviceCode}.`);
                await authManager_1.authManager.saveToken(data.access_token);
                // Notify connected clients (e.g., frontend app)
                wss.clients.forEach(client => {
                    if (client.readyState === client.OPEN) {
                        client.send(JSON.stringify({ event: 'auth_success' }));
                    }
                });
                clearInterval(intervalId);
            }
        }
        catch (error) {
            console.error(`Error during polling for ${deviceCode}:`, error);
        }
    }, pollInterval);
}
