var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var flights_exports = {};
__export(flights_exports, {
  flight: () => flight,
  flightPreview: () => flightPreview,
  flights: () => flights,
  flightsPreview: () => flightsPreview
});
module.exports = __toCommonJS(flights_exports);
var import_map = __toESM(require("@babel/runtime-corejs3/core-js/instance/map"));
var import_set = __toESM(require("@babel/runtime-corejs3/core-js/set"));
var import_for_each = __toESM(require("@babel/runtime-corejs3/core-js/instance/for-each"));
var import_sort = __toESM(require("@babel/runtime-corejs3/core-js/instance/sort"));
var import_from = __toESM(require("@babel/runtime-corejs3/core-js/array/from"));
var import_internals = require("@prisma/internals");
var import_graphql_server = require("@cedarjs/graphql-server");
var import_db = require("../../lib/db");
const LAST_FLIGHTS_PREVIEW_COUNT = 60;
const decodeFlightMetadata = (flight2) => {
  if (flight2.encoding === "base64") {
    try {
      const metadata = JSON.parse(Buffer.from(flight2.encodedMetadata, "base64").toString("utf-8"));
      return metadata;
    } catch (e) {
      import_internals.logger.error(e);
      throw new import_graphql_server.ValidationError(`Invalid metadata for flight ${flight2.id}`);
    }
  }
  throw new import_graphql_server.ValidationError(`Unsupported encoding type ${flight2.encoding}`);
};
const decodeFlightPayload = (flight2) => {
  if (flight2.encoding === "base64") {
    try {
      return Buffer.from(flight2.encodedPayload, "base64").toString("utf-8");
    } catch (e) {
      import_internals.logger.error(e);
      throw new import_graphql_server.ValidationError(`Invalid payload for flight ${flight2.id}`);
    }
  }
  throw new import_graphql_server.ValidationError(`Unsupported encoding type ${flight2.encoding}`);
};
const decodeFlightPerformance = (flight2) => {
  try {
    const payload = decodeFlightPayload(flight2);
    const metadata = decodeFlightMetadata(flight2);
    const performanceMeta = metadata?.["performance"] || {};
    const performance = {
      startedAt: new Date(performanceMeta.startedAt).toISOString(),
      endedAt: new Date(performanceMeta.endedAt).toISOString(),
      duration: performanceMeta.duration || 0,
      sizeInBytes: Buffer.from(payload).length
    };
    return performance;
  } catch (e) {
    import_internals.logger.error(e);
    return {
      startedAt: (/* @__PURE__ */ new Date()).toISOString(),
      endedAt: (/* @__PURE__ */ new Date()).toISOString(),
      duration: 0,
      sizeInBytes: 0
    };
  }
};
const previewFlightPayload = (flight2) => {
  const metadata = decodeFlightMetadata(flight2);
  const id = metadata?.rsc?.rscId || metadata?.rsc?.rsaId || flight2.id;
  return id;
};
const enrichFlight = (flight2) => {
  return {
    ...flight2,
    payload: decodeFlightPayload(flight2),
    preview: previewFlightPayload(flight2),
    metadata: decodeFlightMetadata(flight2),
    performance: decodeFlightPerformance(flight2)
  };
};
const flights = async () => {
  const result = await import_db.db.flight.findMany({
    orderBy: {
      createdAt: "asc"
    }
  });
  return (0, import_map.default)(result).call(result, (flight2) => {
    return enrichFlight(flight2);
  });
};
const flight = async ({
  id
}) => {
  const flight2 = await import_db.db.flight.findUnique({
    where: {
      id
    }
  });
  return {
    ...flight2,
    payload: decodeFlightPayload(flight2),
    preview: previewFlightPayload(flight2),
    metadata: decodeFlightMetadata(flight2),
    performance: decodeFlightPerformance(flight2)
  };
};
const flightPreview = async ({
  id
}) => {
  const result = await import_db.db.flight.findUnique({
    where: {
      id
    }
  });
  const enriched = enrichFlight(result);
  let status = "OK";
  switch (enriched.metadata?.status) {
    case 200:
      status = "OK";
      break;
    case 500:
      status = "ERROR";
      break;
    default:
      status = "WARNING";
  }
  return {
    id: result.id,
    flight: enriched,
    status,
    startedAt: enriched.performance?.startedAt || (/* @__PURE__ */ new Date()).toISOString(),
    endedAt: enriched.performance?.endedAt || (/* @__PURE__ */ new Date()).toISOString(),
    hostname: enriched.metadata?.["hostname"] || "localhost",
    caption: "RSC Payload"
  };
};
const flightsPreview = async () => {
  var _context;
  const result = await import_db.db.flight.findMany({
    orderBy: {
      createdAt: "asc"
    },
    take: LAST_FLIGHTS_PREVIEW_COUNT
  });
  if (!result || result.length === 0) {
    return null;
  }
  const enriched = (0, import_map.default)(result).call(result, (flight2) => {
    return enrichFlight(flight2);
  });
  const firstPerformance = enriched[0]?.performance;
  const lastPerformance = enriched[enriched?.length - 1]?.performance;
  const firstMetadata = enriched[0]?.metadata;
  const lastMetadata = enriched[enriched?.length - 1]?.metadata;
  const overallStatus = lastMetadata?.["status"] || 200;
  let status = "OK";
  switch (overallStatus) {
    case 200:
      status = "OK";
      break;
    case 500:
      status = "ERROR";
      break;
    default:
      status = "WARNING";
  }
  const statuses = new import_set.default();
  (0, import_for_each.default)(enriched).call(enriched, (flight2) => {
    const metadata = flight2.metadata;
    const theStatus = metadata?.["status"] || 200;
    switch (theStatus) {
      case 200:
        statuses.add("OK");
        break;
      case 500:
        statuses.add("ERROR");
        break;
      default:
        statuses.add("WARNING");
    }
  });
  const uniqueStatuses = (0, import_sort.default)(_context = (0, import_from.default)(statuses)).call(_context, (a, b) => a > b ? 1 : -1);
  const caption = `Flights (${enriched.length >= LAST_FLIGHTS_PREVIEW_COUNT ? `last ${LAST_FLIGHTS_PREVIEW_COUNT}` : enriched.length})`;
  return {
    id: "flights-preview",
    flights: enriched,
    status,
    statuses: uniqueStatuses,
    startedAt: firstPerformance?.startedAt || (/* @__PURE__ */ new Date()).toISOString(),
    endedAt: lastPerformance?.endedAt || (/* @__PURE__ */ new Date()).toISOString(),
    hostname: firstMetadata?.["hostname"] || "localhost",
    caption
  };
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  flight,
  flightPreview,
  flights,
  flightsPreview
});
//# sourceMappingURL=flights.js.map
