var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
    if (value !== null && value !== void 0) {
        if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
        var dispose, inner;
        if (async) {
            if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
            dispose = value[Symbol.asyncDispose];
        }
        if (dispose === void 0) {
            if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
            dispose = value[Symbol.dispose];
            if (async) inner = dispose;
        }
        if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
        if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
        env.stack.push({ value: value, dispose: dispose, async: async });
    }
    else if (async) {
        env.stack.push({ async: true });
    }
    return value;
};
var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
    return function (env) {
        function fail(e) {
            env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
            env.hasError = true;
        }
        var r, s = 0;
        function next() {
            while (r = env.stack.pop()) {
                try {
                    if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
                    if (r.dispose) {
                        var result = r.dispose.call(r.value);
                        if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
                    }
                    else s |= 1;
                }
                catch (e) {
                    fail(e);
                }
            }
            if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
            if (env.hasError) throw env.error;
        }
        return next();
    };
})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
    var e = new Error(message);
    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
});
import { NewSessionResponse } from '@axium/core';
import * as io from 'ioium/node';
import { createServer } from 'node:http';
import { createInterface } from 'node:readline/promises';
import { styleText } from 'node:util';
import { config, resolveServerURL } from '../config.js';
import { prefix, setPrefix, setToken } from '../requests.js';
import { getCurrentSession } from '../user.js';
import * as cache from './cache.js';
import { saveConfig } from './config.js';
import * as os from 'node:os';
import $pkg from '../../package.json' with { type: 'json' };
export const clientUA = `Axium Client/${$pkg.version} (${os.type()}; ${process.arch})`;
export async function login(url) {
    const env_1 = { stack: [], error: void 0, hasError: false };
    try {
        const rl = __addDisposableResource(env_1, createInterface({
            input: process.stdin,
            output: process.stdout,
        }), false);
        rl.on('SIGINT', () => io.exit('Aborted.', 7));
        if (prefix[0] != '/')
            url ||= prefix;
        url ||= await rl.question('Axium server URL: ');
        url = resolveServerURL(url);
        setPrefix(url);
        const sessionReady = Promise.withResolvers();
        // eslint-disable-next-line @typescript-eslint/no-misused-promises
        const server = createServer(async (req, res) => {
            res.setHeader('access-control-allow-origin', '*');
            res.setHeader('access-control-allow-methods', '*');
            res.setHeader('access-control-allow-headers', '*');
            if (req.method == 'HEAD' || req.method == 'OPTIONS') {
                res.writeHead(200).end();
                return;
            }
            if (!req.headers['content-type']?.endsWith('/json')) {
                res.writeHead(415).end('Unexpected content type');
                return;
            }
            if (req.method !== 'POST') {
                res.writeHead(405).end('Unexpected request method');
                return;
            }
            const { promise: bodyReady, resolve, reject } = Promise.withResolvers();
            let body = '';
            req.on('data', chunk => (body += chunk.toString()));
            req.on('end', resolve);
            req.on('error', reject);
            try {
                await bodyReady;
                res.writeHead(200).end();
                sessionReady.resolve(NewSessionResponse.parse(JSON.parse(body)));
            }
            catch (e) {
                res.statusCode = 500;
                res.end('Internal server error: ' + io.errorText(e));
                sessionReady.reject(io.errorText(e));
            }
        });
        const serverReady = Promise.withResolvers();
        server.listen(() => {
            const { port } = server.address();
            serverReady.resolve(port);
        });
        server.on('error', e => io.exit('Failed to start local callback server: ' + io.errorText(e), 5));
        const port = await serverReady.promise;
        const authURL = new URL(`/login/client?port=${port}&client=${encodeURIComponent(clientUA)}`, url).href;
        console.log('Authenticate by visiting this URL in your browser: ' + styleText('underline', authURL));
        const { token } = await sessionReady.promise.catch(e => io.exit('Failed to obtain session: ' + e, 6));
        setToken(token);
        server.close();
        const session = await io.track('Verifying session', getCurrentSession().catch(e => io.exit(e, 6)));
        io.debug('Session UUID: ' + session.id);
        console.log(`Welcome ${session.user.name}! Your session is valid until ${session.expires.toLocaleDateString()}.`);
        config.token = token;
        config.server = url;
        saveConfig();
        await cache.update(true);
    }
    catch (e_1) {
        env_1.error = e_1;
        env_1.hasError = true;
    }
    finally {
        __disposeResources(env_1);
    }
}
