package TestHelper;

use strict;
use warnings;
use LWP::UserAgent;
use File::Temp qw(tempfile);
use Digest::SHA qw(sha512);
use Convert::ASN1;

# FreeTSA.org configuration
our $FREETSA_URL = 'https://freetsa.org/tsr';
our $FREETSA_TCP_HOST = 'freetsa.org';
our $FREETSA_TCP_PORT = 318;

sub new {
    my $class = shift;
    my $self = {
        ua => LWP::UserAgent->new(
            timeout => 30,
            agent => 'Crypt-TimestampedData-Test/1.0'
        )
    };
    return bless $self, $class;
}

# Generate a timestamp request (TSQ) for given data
sub create_tsq {
    my ($self, $data) = @_;
    
    # Create SHA-512 hash
    my $hash = sha512($data);
    
    # Create a simple TSQ structure (simplified version)
    # In a real implementation, you'd use proper ASN.1 encoding
    my $tsq_data = pack('H*', '300d020101300906052b0e03021a0500') . $hash;
    
    return $tsq_data;
}

# Get timestamp from FreeTSA using HTTP
sub get_timestamp_http {
    my ($self, $data) = @_;
    
    my $tsq = $self->create_tsq($data);
    
    my $response = $self->{ua}->post($FREETSA_URL, 
        'Content-Type' => 'application/timestamp-query',
        Content => $tsq
    );
    
    if ($response->is_success) {
        return $response->content;
    } else {
        warn "HTTP timestamp request failed: " . $response->status_line;
        return undef;
    }
}

# Get timestamp from FreeTSA using TCP (simplified)
sub get_timestamp_tcp {
    my ($self, $data) = @_;
    
    my $tsq = $self->create_tsq($data);
    
    # For testing purposes, we'll create a mock timestamp response
    # In a real implementation, you'd use proper TCP communication
    return $self->create_mock_timestamp($data);
}

# Create a mock timestamp for testing when FreeTSA is not available
sub create_mock_timestamp {
    my ($self, $data) = @_;
    
    # Create a minimal valid CMS ContentInfo structure for testing
    # This simulates a TimeStampToken (RFC 3161) - pkcs7-signedData
    my $mock_tsr = pack('H*', 
        '308201a006092a864886f70d010702a0819230818f0201013081' .
        '8b06092a864886f70d010701a07e0c7c3082017830820170' .
        '0201013082015c06092a864886f70d010701a0814e0c4c' .
        '3082014830820140020101307c06092a864886f70d010701' .
        'a06f0c6d3082016930820161020101305d06092a864886f70d010701'
    );
    
    return $mock_tsr;
}

# Test if FreeTSA is available
sub is_freetsa_available {
    my $self = shift;
    
    my $response = $self->{ua}->get('https://freetsa.org/');
    return $response->is_success;
}

1;
