<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Tests\User\Import;

use CpCreation\VitiCore\User\Import\ImportedClientFileStorage;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Filesystem\Filesystem;

final class ImportedClientFileStorageTest extends TestCase
{
    private string $projectDirectory;

    protected function setUp(): void
    {
        $this->projectDirectory = sys_get_temp_dir() . '/viti-core-storage-test-' . bin2hex(random_bytes(8));
        mkdir($this->projectDirectory, 0o700, true);
    }

    protected function tearDown(): void
    {
        new Filesystem()->remove($this->projectDirectory);
    }

    public function testItArchivesAndResolvesAnImportedFileOutsideThePublicDirectory(): void
    {
        $source = $this->projectDirectory . '/source.csv';
        file_put_contents($source, "Email;Groupe\nclient@example.com;Club");
        $storage = new ImportedClientFileStorage($this->projectDirectory);

        $storedFile = $storage->archive($source, 'csv');
        $archivedPath = $storage->path($storedFile->filename);

        self::assertFileExists($archivedPath);
        self::assertStringStartsWith($this->projectDirectory . '/var/viti-core/', $archivedPath);
        self::assertSame(filesize($source), $storedFile->size);

        $storage->remove($storedFile->filename);
        self::assertFileDoesNotExist($archivedPath);
    }

    public function testItRejectsAnUnsafeArchiveFilename(): void
    {
        $storage = new ImportedClientFileStorage($this->projectDirectory);

        $this->expectException(\InvalidArgumentException::class);

        $storage->path('../clients.csv');
    }
}
