<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Tests\User\Import;

use CpCreation\VitiCore\User\Import\ClientImportAnalyzer;
use CpCreation\VitiCore\User\Import\ClientImportException;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PHPUnit\Framework\TestCase;

final class ClientImportAnalyzerTest extends TestCase
{
    private array $temporaryFiles = [];

    protected function tearDown(): void
    {
        foreach ($this->temporaryFiles as $temporaryFile) {
            if (is_file($temporaryFile)) {
                unlink($temporaryFile);
            }
        }
    }

    public function testItDetectsColumnsAndAnalyzesASemicolonSeparatedCsv(): void
    {
        $file = $this->temporaryFile('csv');
        file_put_contents($file, implode("\n", [
            "\xEF\xBB\xBFNom;Adresse e-mail;Groupe partenaire",
            'Alice;ALICE@example.com;Professionnels',
            'Bob;adresse-invalide;Particuliers',
            'Charlie;charlie@example.com;',
            'Denise;denise@example.com;Particuliers',
        ]));

        $analysis = new ClientImportAnalyzer()->analyze($file);

        self::assertSame(1, $analysis->headerLine);
        self::assertSame('B', $analysis->emailColumn);
        self::assertSame('Adresse e-mail', $analysis->emailHeader);
        self::assertSame('C', $analysis->groupColumn);
        self::assertSame(['Particuliers', 'Professionnels'], $analysis->sourceGroups);
        self::assertSame(4, $analysis->totalRows);
        self::assertSame(2, $analysis->invalidEmailRows + $analysis->missingGroupRows);
        self::assertCount(2, $analysis->rows);
        self::assertSame('alice@example.com', $analysis->rows[0]->email);
    }

    public function testItDetectsHeadersAfterIntroductoryRowsInAnExcelFile(): void
    {
        $file = $this->temporaryFile('xlsx');
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setCellValue('A1', 'Export clients');
        $sheet->setCellValue('B3', 'Courriel');
        $sheet->setCellValue('D3', 'Groupe');
        $sheet->setCellValue('B4', 'client@example.com');
        $sheet->setCellValue('D4', 'Club');
        new Xlsx($spreadsheet)->save($file);
        $spreadsheet->disconnectWorksheets();

        $analysis = new ClientImportAnalyzer()->analyze($file);

        self::assertSame(3, $analysis->headerLine);
        self::assertSame('B', $analysis->emailColumn);
        self::assertSame('D', $analysis->groupColumn);
        self::assertSame(['Club'], $analysis->sourceGroups);
        self::assertCount(1, $analysis->rows);
    }

    public function testItRejectsAFileWithoutAGroupColumn(): void
    {
        $file = $this->temporaryFile('csv');
        file_put_contents($file, "Email;Nom\nclient@example.com;Client");

        $this->expectException(ClientImportException::class);
        $this->expectExceptionMessage('admin_client_import.error.columns_not_detected');

        new ClientImportAnalyzer()->analyze($file);
    }

    private function temporaryFile(string $extension): string
    {
        $path = sys_get_temp_dir() . '/viti-core-import-test-' . bin2hex(random_bytes(8)) . '.' . $extension;
        $this->temporaryFiles[] = $path;

        return $path;
    }
}
