{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "urn:open-utility-stack:common:reference:1",
  "title": "common/reference@1",
  "description": "The client reference of a command (conventions REF-1 to REF-6) and the reference tuple of a market message (REF-7).",
  "$defs": {
    "ClientReference": {
      "description": "Opaque, chosen by the sender, compared byte for byte; 1 to 128 printable ASCII characters, no space at either end. Its identity is (authenticated sender, value).",
      "type": "string",
      "minLength": 1,
      "maxLength": 128,
      "pattern": "^[!-~]([ -~]*[!-~])?$"
    },
    "Reason": {
      "description": "Why a state was reached: a code a machine decides by, and a sentence a person reads.",
      "type": "object",
      "additionalProperties": false,
      "required": ["code"],
      "properties": {
        "code": { "type": "string", "pattern": "^[a-z0-9]+([._-][a-z0-9]+)*$", "maxLength": 64 },
        "text": { "type": "string", "pattern": "\\S", "maxLength": 200 },
        "codelist": { "description": "Where `code` comes from when it is not the profile's own, such as an EBD or an APERAK code list.", "type": "string", "maxLength": 64 }
      }
    },
    "MarketParty": {
      "type": "object",
      "additionalProperties": false,
      "required": ["id", "role"],
      "properties": {
        "id": { "description": "The 13-digit market partner id (BDEW or GS1).", "type": "string", "pattern": "^[0-9]{13}$" },
        "role": { "description": "The market role, as the EDI@Energy documents name it: LF, NB, MSB, ÜNB, BKV, …", "type": "string", "minLength": 2, "maxLength": 8 }
      }
    },
    "MarketReference": {
      "description": "What identifies one market transaction: never a MaLo or a document number alone (REF-7).",
      "type": "object",
      "additionalProperties": false,
      "required": ["document", "sender", "receiver", "direction"],
      "properties": {
        "document": { "description": "BGM document number of the original message.", "type": "string", "minLength": 1, "maxLength": 35 },
        "transaction": { "description": "The transaction number of the original (the CNI or IDE segment, as the message type puts it). Absent only for ORDERS and ORDRSP (check ids 17xxx and 19xxx), which carry one transaction per message and no such segment; there the document number identifies it.", "type": "string", "minLength": 1, "maxLength": 35 },
        "sender": { "$ref": "#/$defs/MarketParty" },
        "receiver": { "$ref": "#/$defs/MarketParty" },
        "direction": { "enum": ["inbound", "outbound"] },
        "pruefidentifikator": { "description": "The EDI@Energy check id, where the message type has one.", "type": "string", "pattern": "^[0-9]{5}$" }
      },
      "if": { "required": ["pruefidentifikator"], "properties": { "pruefidentifikator": { "pattern": "^(17|19)[0-9]{3}$" } } },
      "else": { "required": ["transaction"] }
    }
  }
}
