<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Persistence\InMemory;

use App\Scolarite\Domain\Model\HomeworkSubmission\HomeworkSubmissionId;
use App\Scolarite\Domain\Model\HomeworkSubmission\SubmissionAttachment;
use App\Scolarite\Domain\Repository\SubmissionAttachmentRepository;

use function array_filter;
use function array_values;

use Override;

final class InMemorySubmissionAttachmentRepository implements SubmissionAttachmentRepository
{
    /** @var array<string, array<SubmissionAttachment>> */
    private array $bySubmissionId = [];

    #[Override]
    public function findBySubmissionId(HomeworkSubmissionId $submissionId): array
    {
        return $this->bySubmissionId[(string) $submissionId] ?? [];
    }

    #[Override]
    public function save(HomeworkSubmissionId $submissionId, SubmissionAttachment $attachment): void
    {
        $this->bySubmissionId[(string) $submissionId][] = $attachment;
    }

    #[Override]
    public function delete(HomeworkSubmissionId $submissionId, SubmissionAttachment $attachment): void
    {
        $key = (string) $submissionId;

        if (!isset($this->bySubmissionId[$key])) {
            return;
        }

        $this->bySubmissionId[$key] = array_values(array_filter(
            $this->bySubmissionId[$key],
            static fn (SubmissionAttachment $a): bool => (string) $a->id !== (string) $attachment->id,
        ));
    }
}
