import { resolveEntityTableName } from "@open-mercato/shared/lib/query/engine";
class QueryIndexScopeError extends Error {
  constructor(message) {
    super(message);
    this.name = "QueryIndexScopeError";
  }
}
async function loadQueryIndexRowScope(em, entityType, recordId) {
  const db = em.getKysely();
  const table = resolveEntityTableName(em, entityType);
  const row = await db.selectFrom(table).select(["organization_id", "tenant_id"]).where("id", "=", recordId).executeTakeFirst();
  if (!row) {
    return null;
  }
  return {
    organizationId: row.organization_id ?? null,
    tenantId: row.tenant_id ?? null
  };
}
function resolveQueryIndexRecordScope(input) {
  const {
    payloadTenantId,
    payloadOrganizationId,
    hasPayloadTenantId,
    hasPayloadOrganizationId,
    rowScope
  } = input;
  if (!rowScope) {
    if (!hasPayloadTenantId || !hasPayloadOrganizationId) {
      throw new QueryIndexScopeError(
        "Query index event is missing tenantId/organizationId and source row scope could not be resolved"
      );
    }
    return {
      tenantId: payloadTenantId ?? null,
      organizationId: payloadOrganizationId ?? null
    };
  }
  if (hasPayloadTenantId && !isSameScopeValue(payloadTenantId, rowScope.tenantId)) {
    throw new QueryIndexScopeError(
      `Query index event tenantId does not match source row scope (payload=${String(payloadTenantId ?? null)}, row=${String(rowScope.tenantId)})`
    );
  }
  if (hasPayloadOrganizationId && !isSameScopeValue(payloadOrganizationId, rowScope.organizationId)) {
    throw new QueryIndexScopeError(
      `Query index event organizationId does not match source row scope (payload=${String(payloadOrganizationId ?? null)}, row=${String(rowScope.organizationId)})`
    );
  }
  return {
    tenantId: hasPayloadTenantId ? payloadTenantId ?? null : rowScope.tenantId,
    organizationId: hasPayloadOrganizationId ? payloadOrganizationId ?? null : rowScope.organizationId
  };
}
function resolveQueryIndexReindexScope(input) {
  if (input.tenantId === void 0 && input.allowAllTenants !== true) {
    throw new QueryIndexScopeError(
      "Query index reindex requires tenantId to be set explicitly; all-tenant reindex must opt in with allowAllTenants=true"
    );
  }
  return {
    tenantId: input.tenantId,
    organizationId: input.organizationId
  };
}
function isSameScopeValue(left, right) {
  return (left ?? null) === right;
}
export {
  QueryIndexScopeError,
  loadQueryIndexRowScope,
  resolveQueryIndexRecordScope,
  resolveQueryIndexReindexScope
};
//# sourceMappingURL=subscriber-scope.js.map
