<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Application\Port\PaginatedStudentImageRightsReader;
use App\Administration\Application\Service\ImageRightsExporter;
use App\Administration\Infrastructure\Security\ImageRightsVoter;
use App\Shared\Application\Port\AuditLogger;
use App\Shared\Infrastructure\Tenant\TenantContext;

use function count;

use Override;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * @implements ProviderInterface<Response>
 */
final readonly class ImageRightsExportProvider implements ProviderInterface
{
    public function __construct(
        private PaginatedStudentImageRightsReader $reader,
        private ImageRightsExporter $exporter,
        private AuthorizationCheckerInterface $authorizationChecker,
        private TenantContext $tenantContext,
        private AuditLogger $auditLogger,
    ) {
    }

    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): Response
    {
        if (!$this->authorizationChecker->isGranted(ImageRightsVoter::VIEW)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à exporter les droits à l\'image.');
        }

        if (!$this->tenantContext->hasTenant()) {
            throw new UnauthorizedHttpException('Bearer', 'Tenant non défini.');
        }

        $tenantId = (string) $this->tenantContext->getCurrentTenantId();
        /** @var array<string, string> $filters */
        $filters = $context['filters'] ?? [];

        $dtos = $this->reader->findAll(
            $tenantId,
            isset($filters['status']) ? (string) $filters['status'] : null,
        );
        $csv = $this->exporter->export($dtos);

        $this->auditLogger->logExport(
            exportType: 'image_rights_csv',
            recordCount: count($dtos),
            targetDescription: 'Export liste droits à l\'image',
        );

        $response = new Response($csv);
        $response->headers->set('Content-Type', 'text/csv; charset=UTF-8');
        $response->headers->set('Content-Disposition', 'attachment; filename="droits-image.csv"');

        return $response;
    }
}
