import { requireAllowedOrigin } from './authRoutes.js';
import { authenticateTerminalRequest } from './terminalRoutes.js';
import { checkPackageUpdate, getVersionInfo, runUpdate } from '../update/packageUpdate.js';
import { clearManualUpdate, readManualUpdate, rememberManualUpdate } from '../update/manualUpdateState.js';
import { checkpointStateBeforeUpdate } from '../update/stateCheckpoint.js';
export async function registerUpdateRoutes(app, config, services) {
    app.get('/api/version', async (request, reply) => {
        const auth = await authenticateTerminalRequest(services.authService, request, reply);
        if (!auth)
            return reply;
        return getVersionInfo(undefined, await readManualUpdate(services.fileStore));
    });
    app.post('/api/update/check', { preHandler: (request, reply) => requireAllowedOrigin(config, request, reply) }, async (request, reply) => {
        const auth = await authenticateTerminalRequest(services.authService, request, reply);
        if (!auth)
            return reply;
        const result = checkPackageUpdate();
        if (!result.error && result.updateAvailable === false) {
            await clearManualUpdate(services.fileStore);
        }
        return result;
    });
    app.post('/api/update', { preHandler: (request, reply) => requireAllowedOrigin(config, request, reply) }, async (request, reply) => {
        const auth = await authenticateTerminalRequest(services.authService, request, reply);
        if (!auth)
            return reply;
        try {
            await checkpointStateBeforeUpdate(config, services.fileStore);
        }
        catch (error) {
            return { ok: false, changed: false, message: stateCheckpointErrorMessage(error), restarting: false };
        }
        const result = runUpdate();
        if (result.manualUpdate) {
            await rememberManualUpdate(services.fileStore, result.manualUpdate);
        }
        else if (result.ok) {
            await clearManualUpdate(services.fileStore);
        }
        return result;
    });
}
function stateCheckpointErrorMessage(error) {
    const detail = error instanceof Error ? error.message : String(error);
    return `State checkpoint failed; update was not started. ${detail}`;
}
//# sourceMappingURL=updateRoutes.js.map