# Copyright (c) 2026 Yuki Kimoto
# MIT License

class HTTP::Tiny::Response {
  version_from HTTP::Tiny;
  
  allow HTTP::Tiny;
  
  use Mojo::Headers;
  use Mojo::Content::Single;
  use Hash;
  
  # Fields
  has tx : ro Mojo::Transaction::HTTP;
  
  has res : virtual ro Mojo::Message::Response
    get {
      return $self->{tx}->res;
    }
  ;
  
  # Class Methods
  private static method new : HTTP::Tiny::Response () {
    
    my $self = new HTTP::Tiny::Response;
    
    return $self;
  }
  
  # Instance Methods
  method protocol : string () {
    
    my $res = $self->res;
    
    my $version = $res->version;
    
    my $protocol = "HTTP/$version";
    
    return $protocol;
  }
  
  method status : int () {
    
    my $res = $self->res;
    
    return $res->code;
  }
  
  method success : int () {
    
    my $res = $self->res;
    
    my $success = $res->is_success;
    
    return $success;
  }
  
  method reason : string () {
    
    my $res = $self->res;
    
    my $reason = $res->message;
    
    return $reason;
  }
  
  method headers : Hash () {
    
    my $res = $self->res;
    
    my $mojo_headers = $res->headers;
    
    # Get headers as a Hash (key is string, value is string or string[])
    # Note: to_hash returns a Hash where values are typically concatenated with commas or stored as arrays
    my $headers_hash = $mojo_headers->to_hash;
    
    return $headers_hash;
  }
  
  method content : string () {
    
    my $res = $self->res;
    
    # Extract the response body using Mojo's content structure
    my $content = $res->content->(Mojo::Content::Single)->asset->slurp;
    
    return $content;
  }
}