"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleApiErrors = void 0;
const common_stuff_1 = require("common-stuff");
const torrent_client_1 = require("../services/torrent-client");
function handleApiErrors(logger) {
    return (err, _req, resp, next) => {
        if (err) {
            if (err instanceof torrent_client_1.TorrentClientError) {
                logger.warn(`Torrent client error: ${err.message}`);
                return resp.status(400).json({
                    error: err.message,
                });
            }
            else if (err instanceof common_stuff_1.HttpError) {
                logger.warn(`${err.status} error: ${err.message}`);
                return resp.status(err.status).json({
                    error: err.message,
                });
            }
            else if (err instanceof Error && 'status' in err) {
                const status = err.status;
                const message = err.message;
                logger.warn(`${status} error: ${message}`);
                return resp.status(status).json({
                    error: message,
                });
            }
            else if (String(err).includes('JSON at position')) {
                logger.warn(String(err));
                resp.status(400).json({
                    error: 'invalid JSON',
                });
            }
            else {
                logger.error(String(err));
                return resp.status(500).json({
                    error: 'unknown error',
                });
            }
        }
        next(err);
    };
}
exports.handleApiErrors = handleApiErrors;
