///|
/// Pluggable PostgreSQL byte-stream transport abstraction.
/// Production Native/Wasm connections use TCP (with optional TLS upgrade); tests may inject `MockPgTransport`.
pub(open) trait PgTransport {
  async fn write_all(Self, payload : Bytes) -> Unit raise @codec.DataError
  async fn read_chunk(Self) -> Bytes? raise @codec.DataError
  async fn close(Self) -> Unit
}

///|
/// Transport factory & out-of-band cancel callback used by `PgDriver`.
pub struct PgConnector {
  open : async (PgConfig) -> &PgTransport raise @codec.DataError
  cancel : async (PgConfig, Int32, Int32) -> Unit
}

///|
pub fn PgConnector::PgConnector(
  open~ : async (PgConfig) -> &PgTransport raise @codec.DataError,
  cancel~ : async (PgConfig, Int32, Int32) -> Unit = (_, _, _) => (),
) -> PgConnector {
  { open, cancel, }
}

///|
/// Deterministic in-memory mock transport for unit testing PG Wire v3 handshakes,
/// prepared statement caching, transactions, and cancellation propagation.
pub struct MockPgTransport {
  priv written : Array[Bytes]
  priv responses : Array[Bytes]
  priv mut responder : ((Bytes) -> Array[Bytes])?
  priv mut read_idx : Int32
  priv mut closed : Bool
}

///|
pub fn MockPgTransport::MockPgTransport(
  responses~ : Array[Bytes] = [],
  responder? : (Bytes) -> Array[Bytes],
) -> MockPgTransport {
  { written: [], responses, responder, read_idx: 0, closed: false, }
}

///|
pub fn MockPgTransport::written_frames(self : MockPgTransport) -> Array[Bytes] {
  self.written.copy()
}

///|
pub fn MockPgTransport::is_closed(self : MockPgTransport) -> Bool {
  self.closed
}

///|
pub fn MockPgTransport::push_response(
  self : MockPgTransport,
  chunk : Bytes,
) -> Unit {
  self.responses.push(chunk)
}

///|
pub fn MockPgTransport::set_responder(
  self : MockPgTransport,
  f : (Bytes) -> Array[Bytes],
) -> Unit {
  self.responder = Some(f)
}

///|
pub impl PgTransport for MockPgTransport with fn write_all(self, payload) -> Unit raise @codec.DataError {
  if self.closed {
    raise @codec.DataError::ConnectionFailed("mock PG transport closed")
  }
  self.written.push(payload)
  match self.responder {
    Some(f) =>
      for resp in f(payload) {
        self.responses.push(resp)
      }
    None => ()
  }
}

///|
pub impl PgTransport for MockPgTransport with fn read_chunk(self) -> Bytes? raise @codec.DataError {
  @async.pause()
  if self.read_idx < self.responses.length() {
    let chunk = self.responses[self.read_idx]
    self.read_idx += 1
    Some(chunk)
  } else {
    None
  }
}

///|
pub impl PgTransport for MockPgTransport with fn close(self) -> Unit {
  @async.pause()
  self.closed = true
}