var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import NotAuthenticatedException from "../../Types/Exception/NotAuthenticatedException";
import TelemetryIngestionKeyService from "../../Server/Services/TelemetryIngestionKeyService";
import Response from "../Utils/Response";
import logger, { getLogAttributesFromRequest } from "../Utils/Logger";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import SpanUtil from "../Utils/Telemetry/SpanUtil";
export default class TelemetryIngest {
    static async isAuthorizedServiceMiddleware(req, res, next) {
        try {
            // check header.
            let oneuptimeToken = req.headers["x-oneuptime-token"];
            // if x-oneuptime-service-token header is present then use that as token.
            if (!oneuptimeToken) {
                oneuptimeToken = req.headers["x-oneuptime-service-token"];
            }
            // if x-oneuptime-ingestion-key header is present then use that as token.
            if (!oneuptimeToken) {
                oneuptimeToken = req.headers["x-oneuptime-ingestion-key"];
            }
            if (!oneuptimeToken) {
                logger.error("Missing header: x-oneuptime-token", getLogAttributesFromRequest(req));
                /*
                 * 401 is deliberate: the OTLP spec classifies it as
                 * non-retryable, so compliant SDKs / collectors surface the
                 * error in their own logs instead of retry-storming. A silent
                 * 200 here would make the client believe the data landed and
                 * leave the user staring at empty dashboards with no clue why.
                 */
                return Response.sendErrorResponse(req, res, new NotAuthenticatedException("Missing ingestion token. Send your OneUptime telemetry ingestion key in the x-oneuptime-token header."));
            }
            const projectId = await TelemetryIngestionKeyService.getProjectIdFromSecretKey(oneuptimeToken.toString());
            if (!projectId) {
                logger.error("Invalid service token: " + oneuptimeToken, getLogAttributesFromRequest(req));
                /*
                 * 401 is deliberate (see the missing-token branch above): a
                 * silent 200 drops the payload while the client believes the
                 * export succeeded. The token value is logged server-side but
                 * intentionally not echoed back in the response body.
                 */
                return Response.sendErrorResponse(req, res, new NotAuthenticatedException("Invalid ingestion token. Send a valid OneUptime telemetry ingestion key in the x-oneuptime-token header."));
            }
            req.projectId = projectId;
            // Tag span with project context for telemetry ingestion observability
            SpanUtil.addAttributesToCurrentSpan({
                projectId: projectId.toString(),
            });
            next();
        }
        catch (err) {
            return next(err);
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object, Function]),
    __metadata("design:returntype", Promise)
], TelemetryIngest, "isAuthorizedServiceMiddleware", null);
//# sourceMappingURL=TelemetryIngest.js.map