// Copyright 2026 PaiGack
// Licensed under the Apache License, Version 2.0.
// Ported from jlaffaye/ftp (ISC License), see LICENSE-THIRD-PARTY.

// Package: `PaiGack/ftp/core` — pure values and parsers, no IO.

///|
/// Error type for every failure that is produced by the FTP protocol layer
/// itself (as opposed to failures raised by the underlying IO stack, which
/// bubble up untouched so callers can still inspect the OS error).
#derive(@debug.Debug)
pub(all) suberror FtpError {
  /// The server answered with a status code we did not expect.
  ServerError(code~ : Int32, msg~ : String)
  /// A command argument contains `\r` or `\n` and was refused before any
  /// byte reached the socket (command injection guard).
  InvalidCommand(arg~ : String)
  /// A `LIST` line could not be recognised by any of the four parsers.
  UnsupportedListLine(line~ : String)
  /// A date field inside a `LIST` line has an unrecognised shape.
  UnsupportedListDate(field~ : String)
  /// Generic parsing failure, carries the underlying reason.
  ParseError(msg~ : String)
  /// The server did not answer within the configured deadline.
  ///
  /// Distinct from `ServerError` on purpose: nothing was answered, so there is
  /// no status code to report. It exists so that a silent peer fails with an
  /// error naming the wait instead of hanging, and so that the async runtime
  /// never mistakes the wait for a deadlock.
  RequestTimeout
}

///|
/// `FtpError` promotes its `Debug` methods as regular methods; declare the
/// promotion explicitly so the deprecation warning stays away.
pub extend FtpError with @debug.Debug::{to_repr}

///|
/// A one-line human description of an `FtpError`, for diagnostics that go to
/// stderr. `Debug` is for debugging -- it spells the package path, which makes
/// a log line read `PaiGack/ftp/core.FtpError.ServerError` instead of
/// `the server answered 500`.
pub fn describe_error(err : Error) -> String {
  match err {
    FtpError::ServerError(code~, msg~) => "the server answered \{code}: \{msg}"
    FtpError::InvalidCommand(arg~) =>
      "refused to send '\{arg}' (contains CR/LF)"
    FtpError::UnsupportedListLine(line~) => "unrecognised listing line: \{line}"
    FtpError::UnsupportedListDate(field~) => "unrecognised date field: \{field}"
    FtpError::ParseError(msg~) => "malformed reply: \{msg}"
    FtpError::RequestTimeout => "the server did not answer in time"
    _ => "\{err}"
  }
}

///|
/// Aggregation of several failures that happened during one logical
/// operation. This mirrors Go's `errors.Join`: the upstream implementation
/// deliberately keeps *every* error (transfer + close + status read) instead
/// of returning as soon as the first one shows up.
#derive(@debug.Debug)
pub(all) suberror FtpErrors {
  /// All errors of a single operation, in the order they occurred.
  MultipleErrors(errors~ : Array[Error])
}

///|
/// `FtpErrors` promotes its `Debug` methods as regular methods; declare the
/// promotion explicitly so the deprecation warning stays away.
pub extend FtpErrors with @debug.Debug::{to_repr}

///|
/// Build an aggregated error, collapsing the trivial cases so callers do not
/// have to care about them:
/// - no error at all -> `None`
/// - exactly one error -> that error itself
/// - otherwise -> `FtpErrors::MultipleErrors`
pub fn join_errors(errors : Array[Error]) -> Error? {
  match errors {
    [] => None
    [e] => Some(e)
    _ => Some(FtpErrors::MultipleErrors(errors~))
  }
}

///|
/// Return every error carried by an aggregate, or the error itself when it is
/// not an aggregate. Useful for tests and for re-raising partial failures.
pub fn flatten_errors(err : Error) -> Array[Error] {
  match err {
    FtpErrors::MultipleErrors(errors~) => errors
    _ => [err]
  }
}