import { NextResponse } from "next/server";
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { InboxProposal, InboxProposalAction } from "../data/entities.js";
import { resolveOptionalEventBus } from "../lib/eventBus.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("inbox_ops");
async function resolveRequestContext(req) {
  const auth = await getAuthFromRequest(req);
  if (!auth?.sub || !auth?.tenantId || !auth?.orgId) {
    throw new UnauthorizedError();
  }
  const container = await createRequestContainer();
  const em = container.resolve("em").fork();
  return {
    auth,
    userId: auth.sub,
    tenantId: auth.tenantId,
    organizationId: auth.orgId,
    scope: { tenantId: auth.tenantId, organizationId: auth.orgId },
    em,
    container,
    eventBus: resolveOptionalEventBus(container)
  };
}
function extractPathSegment(url, afterSegment) {
  const segments = url.pathname.split("/");
  const index = segments.indexOf(afterSegment);
  return index >= 0 ? segments[index + 1] || null : null;
}
async function resolveActionAndProposal(url, ctx) {
  const proposalId = extractPathSegment(url, "proposals");
  const actionId = extractPathSegment(url, "actions");
  if (!proposalId || !actionId) {
    return NextResponse.json({ error: "Missing IDs" }, { status: 400 });
  }
  const action = await findOneWithDecryption(
    ctx.em,
    InboxProposalAction,
    {
      id: actionId,
      proposalId,
      organizationId: ctx.organizationId,
      tenantId: ctx.tenantId,
      deletedAt: null
    },
    void 0,
    ctx.scope
  );
  if (!action) {
    return NextResponse.json({ error: "Action not found" }, { status: 404 });
  }
  const proposal = await findOneWithDecryption(
    ctx.em,
    InboxProposal,
    {
      id: proposalId,
      organizationId: ctx.organizationId,
      tenantId: ctx.tenantId,
      isActive: true,
      deletedAt: null
    },
    void 0,
    ctx.scope
  );
  if (!proposal) {
    return NextResponse.json({ error: "Proposal has been superseded by a newer extraction" }, { status: 409 });
  }
  return { action, proposal };
}
async function resolveProposal(url, ctx) {
  const proposalId = extractPathSegment(url, "proposals");
  if (!proposalId) {
    return NextResponse.json({ error: "Missing proposal ID" }, { status: 400 });
  }
  const proposal = await findOneWithDecryption(
    ctx.em,
    InboxProposal,
    {
      id: proposalId,
      organizationId: ctx.organizationId,
      tenantId: ctx.tenantId,
      isActive: true,
      deletedAt: null
    },
    void 0,
    ctx.scope
  );
  if (!proposal) {
    return NextResponse.json({ error: "Proposal not found" }, { status: 404 });
  }
  return proposal;
}
function toExecutionContext(ctx, entities) {
  return {
    em: ctx.em,
    userId: ctx.userId,
    tenantId: ctx.tenantId,
    organizationId: ctx.organizationId,
    eventBus: ctx.eventBus,
    container: ctx.container,
    auth: ctx.auth,
    entities
  };
}
function handleRouteError(err, label) {
  if (err instanceof UnauthorizedError) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  logger.error("Request failed", { label, err });
  return NextResponse.json({ error: `Failed to ${label}` }, { status: 500 });
}
function isErrorResponse(value) {
  return value instanceof NextResponse;
}
function resolveCrossModuleEntities(container) {
  const entities = {};
  try {
    entities.CustomerEntity = container.resolve("CustomerEntity");
  } catch {
  }
  try {
    entities.SalesOrder = container.resolve("SalesOrder");
  } catch {
  }
  try {
    entities.SalesShipment = container.resolve("SalesShipment");
  } catch {
  }
  try {
    entities.SalesChannel = container.resolve("SalesChannel");
  } catch {
  }
  try {
    entities.Dictionary = container.resolve("Dictionary");
  } catch {
  }
  try {
    entities.DictionaryEntry = container.resolve("DictionaryEntry");
  } catch {
  }
  return entities;
}
class UnauthorizedError extends Error {
  constructor() {
    super("Unauthorized");
  }
}
export {
  UnauthorizedError,
  extractPathSegment,
  handleRouteError,
  isErrorResponse,
  resolveActionAndProposal,
  resolveCrossModuleEntities,
  resolveProposal,
  resolveRequestContext,
  toExecutionContext
};
//# sourceMappingURL=routeHelpers.js.map
