######################################################################
#
# t/003_ltsv_file.t - LTSV file I/O tests
#
######################################################################

BEGIN {
    unshift @INC, 'lib';
    $| = 1;
    print "1..8\n";
}

use LTSV::LINQ;

my $testno = 1;

sub ok {
    my($test, $name) = @_;
    printf "%s %d - %s\n", ($test ? 'ok' : 'not ok'), $testno++, $name || '';
    return $test;
}

# Create test LTSV file
my $testfile = 't/test_data.ltsv';
open(FH, "> $testfile") or die "Cannot create test file: $!";
print FH "time:2026-01-01T10:00:00\tstatus:200\turl:/home\tbytes:1024\n";
print FH "time:2026-01-01T10:01:00\tstatus:404\turl:/missing\tbytes:512\n";
print FH "time:2026-01-01T10:02:00\tstatus:200\turl:/about\tbytes:2048\n";
print FH "\n";  # Empty line
print FH "time:2026-01-01T10:03:00\tstatus:500\turl:/error\tbytes:256\n";
close FH;

# Test 1: FromLTSV reads file
my $query = LTSV::LINQ->FromLTSV($testfile);
ok(defined($query), 'FromLTSV creates query object');

# Test 2: Read all records
my @all = $query->ToArray();
ok(@all == 4, 'FromLTSV reads correct number of records');

# Test 3: Parse fields correctly
ok($all[0]{status} eq '200' && $all[0]{url} eq '/home', 
   'FromLTSV parses fields correctly');

# Test 4: Handle empty lines
ok($all[3]{status} eq '500', 'FromLTSV skips empty lines');

# Test 5: Field with colon in value
open(FH, "> $testfile") or die;
print FH "url:http://example.com:8080\tstatus:200\n";
close FH;

my @colon_test = LTSV::LINQ->FromLTSV($testfile)->ToArray();
ok($colon_test[0]{url} eq 'http://example.com:8080',
   'FromLTSV handles colons in values');

# Test 6: ToLTSV writes file
my $outfile = 't/test_output.ltsv';
LTSV::LINQ->From([
    {status => 200, url => '/home'},
    {status => 404, url => '/missing'},
])->ToLTSV($outfile);

open(FH, "< $outfile") or die;
my @lines = <FH>;
close FH;

ok(@lines == 2, 'ToLTSV writes correct number of lines');

# Test 7: ToLTSV formats correctly
ok($lines[0] =~ /status:200/ && $lines[0] =~ /url:\/home/,
   'ToLTSV formats fields correctly');

# Test 8: Round-trip
my @roundtrip = LTSV::LINQ->FromLTSV($outfile)->ToArray();
ok($roundtrip[0]{status} eq '200' && $roundtrip[1]{status} eq '404',
   'Round-trip preserves data');

# Clean up
unlink $testfile;
unlink $outfile;
