<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Persistence\InMemory;

use App\Scolarite\Domain\Model\Homework\HomeworkAttachment;
use App\Scolarite\Domain\Model\Homework\HomeworkId;
use App\Scolarite\Domain\Repository\HomeworkAttachmentRepository;

use function array_fill_keys;
use function array_filter;
use function array_map;
use function array_values;

use Override;

final class InMemoryHomeworkAttachmentRepository implements HomeworkAttachmentRepository
{
    /** @var array<string, array<HomeworkAttachment>> */
    private array $byHomeworkId = [];

    #[Override]
    public function findByHomeworkId(HomeworkId $homeworkId): array
    {
        return $this->byHomeworkId[(string) $homeworkId] ?? [];
    }

    #[Override]
    public function hasAttachments(HomeworkId ...$homeworkIds): array
    {
        $ids = array_map(static fn (HomeworkId $id): string => (string) $id, $homeworkIds);
        $result = array_fill_keys($ids, false);

        foreach ($ids as $id) {
            $result[$id] = isset($this->byHomeworkId[$id]) && $this->byHomeworkId[$id] !== [];
        }

        return $result;
    }

    #[Override]
    public function save(HomeworkId $homeworkId, HomeworkAttachment $attachment): void
    {
        $this->byHomeworkId[(string) $homeworkId][] = $attachment;
    }

    #[Override]
    public function delete(HomeworkId $homeworkId, HomeworkAttachment $attachment): void
    {
        $key = (string) $homeworkId;

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

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