///|
/// PostgreSQL TLS negotiation mode.
#non_exhaustive
#derive(Debug, Eq)
pub(all) enum SslMode {
  Disable
  Prefer
  Require
}

///|
/// PostgreSQL driver connection and pool configuration.
#derive(Debug, Eq)
pub(all) struct PgConfig {
  host : String
  port : Int32
  user : String
  password : String
  database : String
  ssl_mode : SslMode
  connect_timeout_ms : Int32
  cancel_timeout_ms : Int32
  statement_cache_size : Int32
  pool : @pool.PoolConfig
  application_name : String
}

///|
pub fn PgConfig::PgConfig(
  host~ : String = "127.0.0.1",
  port~ : Int32 = 5432,
  user~ : String = "postgres",
  password~ : String = "",
  database~ : String = "postgres",
  ssl_mode~ : SslMode = SslMode::Prefer,
  connect_timeout_ms~ : Int32 = 5000,
  cancel_timeout_ms~ : Int32 = 1500,
  statement_cache_size~ : Int32 = 256,
  pool~ : @pool.PoolConfig = @pool.PoolConfig::PoolConfig(),
  application_name~ : String = "ciallo-driver-pg",
) -> PgConfig {
  {
    host,
    port,
    user,
    password,
    database,
    ssl_mode,
    connect_timeout_ms,
    cancel_timeout_ms,
    statement_cache_size,
    pool,
    application_name,
  }
}

///|
/// Parses a `postgres://` or `postgresql://` connection URL into `PgConfig`.
pub fn PgConfig::from_url(dsn : StringView) -> PgConfig raise @codec.DataError {
  let raw = dsn.trim().to_owned()
  let rest = if raw.has_prefix("postgres://") {
    raw[11:].to_owned()
  } else if raw.has_prefix("postgresql://") {
    raw[13:].to_owned()
  } else {
    raise @codec.DataError::ConnectionFailed(
      "invalid PostgreSQL URL scheme (expected postgres:// or postgresql://)",
    )
  }
  let (authority_and_path, query_str) = match rest.find("?") {
    Some(idx) => (rest[:idx].to_owned(), rest[idx + 1:].to_owned())
    None => (rest, "")
  }
  let (authority, path_part) = match authority_and_path.find("/") {
    Some(idx) =>
      (
        authority_and_path[:idx].to_owned(),
        authority_and_path[idx + 1:].to_owned(),
      )
    None => (authority_and_path, "")
  }
  let (userinfo, hostport) = match authority.rev_find("@") {
    Some(idx) => (authority[:idx].to_owned(), authority[idx + 1:].to_owned())
    None => ("", authority)
  }
  let mut user = "postgres"
  let mut password = ""
  if !userinfo.is_empty() {
    match userinfo.find(":") {
      Some(idx) => {
        user = @url.percent_decode(userinfo[:idx]) catch {
          _ => userinfo[:idx].to_owned()
        }
        password = @url.percent_decode(userinfo[idx + 1:]) catch {
          _ => userinfo[idx + 1:].to_owned()
        }
      }
      None => user = @url.percent_decode(userinfo) catch { _ => userinfo }
    }
  }
  let mut host = "127.0.0.1"
  let mut port : Int32 = 5432
  if !hostport.is_empty() {
    if hostport.has_prefix("[") {
      match hostport.find("]") {
        Some(end_idx) => {
          host = hostport[1:end_idx].to_owned()
          let tail = hostport[end_idx + 1:].to_owned()
          if tail.has_prefix(":") {
            port = @string.parse_int(tail[1:]) catch {
              _ =>
                raise @codec.DataError::ConnectionFailed(
                  "invalid PostgreSQL port in URL",
                )
            }
          }
        }
        None =>
          raise @codec.DataError::ConnectionFailed("unterminated IPv6 host")
      }
    } else {
      match hostport.rev_find(":") {
        Some(idx) => {
          host = hostport[:idx].to_owned()
          port = @string.parse_int(hostport[idx + 1:]) catch {
            _ =>
              raise @codec.DataError::ConnectionFailed(
                "invalid PostgreSQL port in URL",
              )
          }
        }
        None => host = hostport
      }
    }
  }
  let database = if path_part.is_empty() {
    user
  } else {
    @url.percent_decode(path_part) catch {
      _ => path_part
    }
  }
  let mut ssl_mode = SslMode::Prefer
  let mut application_name = "ciallo-driver-pg"
  if !query_str.is_empty() {
    for pair in query_str.split("&") {
      let s = pair.to_owned()
      match s.find("=") {
        Some(idx) => {
          let k = s[:idx].to_owned()
          let v = @url.percent_decode(s[idx + 1:]) catch {
            _ => s[idx + 1:].to_owned()
          }
          if k == "sslmode" {
            match v.to_lower() {
              "disable" => ssl_mode = SslMode::Disable
              "require" | "verify-ca" | "verify-full" =>
                ssl_mode = SslMode::Require
              _ => ssl_mode = SslMode::Prefer
            }
          } else if k == "application_name" {
            application_name = v
          }
        }
        None => ()
      }
    }
  }
  PgConfig::PgConfig(
    host~,
    port~,
    user~,
    password~,
    database~,
    ssl_mode~,
    application_name~,
  )
}