<?php

declare(strict_types=1);

namespace App\Administration\Application\Service;

use App\Administration\Application\Query\GetStudentsImageRights\StudentImageRightsDto;
use RuntimeException;

final readonly class ImageRightsExporter
{
    /**
     * @param StudentImageRightsDto[] $students
     */
    public function export(array $students): string
    {
        $handle = fopen('php://temp', 'r+');

        if ($handle === false) {
            throw new RuntimeException('Impossible d\'ouvrir le flux CSV.');
        }

        fputcsv($handle, ['Nom', 'Prénom', 'Classe', 'Statut'], separator: ';', escape: '\\');

        foreach ($students as $student) {
            fputcsv($handle, [
                $student->lastName,
                $student->firstName,
                $student->className ?? '',
                $student->imageRightsStatusLabel,
            ], separator: ';', escape: '\\');
        }

        rewind($handle);
        $csv = stream_get_contents($handle);
        fclose($handle);

        // BOM UTF-8 pour que Excel Windows affiche correctement les accents
        return "\xEF\xBB\xBF" . ($csv !== false ? $csv : '');
    }
}
