///|
/// PostgreSQL OID <-> `SqlValue` encoding/decoding, SQLSTATE -> `DataError` mapping,
/// and `CommandComplete` tag parser.

///|
pub let oid_bool : Int32 = 16

///|
pub let oid_bytea : Int32 = 17

///|
pub let oid_int8 : Int32 = 20

///|
pub let oid_int2 : Int32 = 21

///|
pub let oid_int4 : Int32 = 23

///|
pub let oid_text : Int32 = 25

///|
pub let oid_json : Int32 = 114

///|
pub let oid_float4 : Int32 = 700

///|
pub let oid_float8 : Int32 = 701

///|
pub let oid_varchar : Int32 = 1043

///|
pub let oid_numeric : Int32 = 1700

///|
pub let oid_uuid : Int32 = 2950

///|
pub let oid_jsonb : Int32 = 3802

///|
fn hex_char_val(b : Byte) -> Int32? {
  let c = b.to_int()
  if c >= 48 && c <= 57 {
    Some(c - 48)
  } else if c >= 97 && c <= 102 {
    Some(c - 87)
  } else if c >= 65 && c <= 70 {
    Some(c - 55)
  } else {
    None
  }
}

///|
fn encode_pg_bytea_hex(data : BytesView) -> Bytes {
  let hex = @crypto.bytes_to_hex(data)
  @utf8.encode("\\x\{hex}")
}

///|
fn decode_pg_bytea(raw : BytesView) -> Bytes raise @codec.DataError {
  if raw.length() >= 2 && raw[0] == b'\\' && raw[1] == b'x' {
    let hex_len = raw.length() - 2
    if hex_len % 2 != 0 {
      raise @codec.DataError::DecodeFailed(
        field="bytea",
        message="odd-length hex bytea literal",
      )
    }
    let out : Array[Byte] = []
    let mut i = 2
    while i < raw.length() {
      match (hex_char_val(raw[i]), hex_char_val(raw[i + 1])) {
        (Some(hi), Some(lo)) => out.push(((hi << 4) | lo).to_byte())
        _ =>
          raise @codec.DataError::DecodeFailed(
            field="bytea",
            message="invalid hex character in bytea",
          )
      }
      i += 2
    }
    Bytes::from_array(out)
  } else {
    raw.to_owned()
  }
}

///|
/// Encodes a `SqlValue` into PostgreSQL text-format wire parameter bytes (`None` for SQL `NULL`).
pub fn encode_sql_param(val : @orm_schema.SqlValue) -> Bytes? {
  match val {
    @orm_schema.SqlValue::Null => None
    @orm_schema.SqlValue::Bool(b) =>
      Some(@utf8.encode(if b { "true" } else { "false" }))
    @orm_schema.SqlValue::Int32(n) => Some(@utf8.encode(n.to_string()))
    @orm_schema.SqlValue::Int64(n) => Some(@utf8.encode(n.to_string()))
    @orm_schema.SqlValue::Double(d) => Some(@utf8.encode(d.to_string()))
    @orm_schema.SqlValue::Text(s) => Some(@utf8.encode(s))
    @orm_schema.SqlValue::Bytes(b) => Some(encode_pg_bytea_hex(b[:]))
    @orm_schema.SqlValue::Json(j) => Some(@utf8.encode(j.stringify()))
  }
}

///|
/// Decodes a PostgreSQL text-format column cell using its `FieldDesc` OID.
pub fn decode_sql_cell(
  field : FieldDesc,
  cell : Bytes?,
) -> @orm_schema.SqlValue raise @codec.DataError {
  match cell {
    None => @orm_schema.SqlValue::Null
    Some(raw) =>
      if field.type_oid == oid_bytea {
        @orm_schema.SqlValue::Bytes(decode_pg_bytea(raw[:]))
      } else {
        let text = @utf8.decode(raw[:]) catch {
          _ =>
            raise @codec.DataError::DecodeFailed(
              field=field.name,
              message="invalid UTF-8 column value",
            )
        }
        match field.type_oid {
          16 =>
            @orm_schema.SqlValue::Bool(
              text == "t" || text == "true" || text == "1",
            )
          21 | 23 => {
            let n = @string.parse_int(text) catch {
              _ =>
                raise @codec.DataError::DecodeFailed(
                  field=field.name,
                  message="invalid Int32 value '\{text}'",
                )
            }
            @orm_schema.SqlValue::Int32(n)
          }
          20 => {
            let n = @string.parse_int64(text) catch {
              _ =>
                raise @codec.DataError::DecodeFailed(
                  field=field.name,
                  message="invalid Int64 value '\{text}'",
                )
            }
            @orm_schema.SqlValue::Int64(n)
          }
          700 | 701 => {
            let d = @string.parse_double(text) catch {
              _ =>
                raise @codec.DataError::DecodeFailed(
                  field=field.name,
                  message="invalid Double value '\{text}'",
                )
            }
            @orm_schema.SqlValue::Double(d)
          }
          114 | 3802 => {
            let j = @json.parse(text) catch {
              _ =>
                raise @codec.DataError::DecodeFailed(
                  field=field.name,
                  message="invalid JSON value",
                )
            }
            @orm_schema.SqlValue::Json(j)
          }
          _ => @orm_schema.SqlValue::Text(text)
        }
      }
  }
}

///|
/// Decodes a `DataRow` using a prior `RowDescription` into a `@orm_schema.SqlRow`.
pub fn decode_sql_row(
  fields : Array[FieldDesc],
  cells : Array[Bytes?],
) -> @orm_schema.SqlRow raise @codec.DataError {
  let cols : Array[String] = Array(capacity=fields.length())
  for i in 0.. @orm_schema.SqlRow raise @codec.DataError {
  if fields.length() != cells.length() {
    raise @codec.DataError::ProtocolError(
      "RowDescription field count (\{fields.length()}) != DataRow cell count (\{cells.length()})",
    )
  }
  let vals : Array[@orm_schema.SqlValue] = Array(capacity=fields.length())
  for i in 0.. @codec.DataError {
  let detail_text = match err.detail {
    Some(d) => "\{err.message} (\{d})"
    None => err.message
  }
  match err.code {
    "23505" =>
      @codec.DataError::UniqueViolation(
        constraint=err.constraint.unwrap_or("pg_unique"),
        detail=detail_text,
      )
    "23503" =>
      @codec.DataError::ForeignKeyViolation(
        constraint=err.constraint.unwrap_or("pg_fk"),
        detail=detail_text,
      )
    "40001" => @codec.DataError::SerializationFailure(detail=detail_text)
    "28P01" | "28000" => @codec.DataError::AuthFailed(detail_text)
    "57014" => @codec.DataError::Timeout(op="pg_query_canceled", elapsed_ms=0L)
    _ => @codec.DataError::BackendError(code=err.code, message=detail_text)
  }
}

///|
/// Extracts the rows-affected count from a PostgreSQL `CommandComplete` tag
/// (e.g., `"INSERT 0 1"`, `"UPDATE 5"`, `"DELETE 3"`, `"SELECT 10"`).
pub fn parse_command_complete_rows(tag : StringView) -> Int64 {
  let trimmed = tag.trim().to_owned()
  match trimmed.rev_find(" ") {
    Some(idx) => {
      let last = trimmed[idx + 1:].to_owned()
      @string.parse_int64(last) catch {
        _ => 0L
      }
    }
    None => 0L
  }
}