<?php

declare(strict_types=1);

namespace Dalten\RuianToUir\Tests\Unit\Writer;

use Dalten\RuianToUir\Converter\Result\AddRecord;
use Dalten\RuianToUir\Formatter\PlainText;
use Dalten\RuianToUir\Writer\MultipleFiles;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\TestCase;
use Dalten\RuianToUir\Writer\MultipleFiles as SUT;

#[CoversClass(SUT::class)]
final class MultipleFilesTest extends TestCase
{
    public function testOutputsAddressItemDataWithSpecifiedFormatOnePerLine(): void
    {
        $dir = dirname(__DIR__, 3) . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR . 'test';
        if (!is_dir($dir)) {
            $this->assertTrue(mkdir($dir, 0777, true) || is_dir($dir));
        }

        try {
            $formatter = new PlainText();
            $writer = new MultipleFiles($formatter, $dir, 'txt');

            $data1 = new AddRecord('Address', 1, ['foo' => 'bar']);
            $data2 = new AddRecord('Address', 2, ['foo' => 'baz']);

            $writer->write($data1, 'Address');
            $writer->write($data2, 'Address');

            $file = $dir . DIRECTORY_SEPARATOR . 'Address.txt';
            $this->assertFileExists($file);
            $content = file_get_contents($file);
            $expected = "Address;ADD;foo=bar\n" . "Address;ADD;foo=baz\n";
            // PHP_EOL inside writer is platform-specific; normalise both
            $content = str_replace(["\r\n", "\r"], "\n", (string) $content);

            $this->assertSame($expected, $content);
        } finally {
            // cleanup
            if (file_exists($dir . DIRECTORY_SEPARATOR . 'Address.txt')) {
                unlink($dir . DIRECTORY_SEPARATOR . 'Address.txt');
            }
    }
    }
}
