<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Persistence\InMemory;

use App\Scolarite\Domain\Model\Homework\HomeworkId;
use App\Scolarite\Domain\Model\Homework\HomeworkRuleException;
use App\Scolarite\Domain\Repository\HomeworkRuleExceptionRepository;
use App\Shared\Domain\Tenant\TenantId;

use function array_filter;
use function array_map;
use function array_unique;
use function array_values;

use Override;

final class InMemoryHomeworkRuleExceptionRepository implements HomeworkRuleExceptionRepository
{
    /** @var array<string, HomeworkRuleException> */
    private array $byId = [];

    #[Override]
    public function save(HomeworkRuleException $exception): void
    {
        $this->byId[(string) $exception->id] = $exception;
    }

    #[Override]
    public function findByHomework(HomeworkId $homeworkId, TenantId $tenantId): array
    {
        return array_values(array_filter(
            $this->byId,
            static fn (HomeworkRuleException $e): bool => $e->homeworkId->equals($homeworkId)
                && $e->tenantId->equals($tenantId),
        ));
    }

    #[Override]
    public function findByTenant(TenantId $tenantId): array
    {
        return array_values(array_filter(
            $this->byId,
            static fn (HomeworkRuleException $e): bool => $e->tenantId->equals($tenantId),
        ));
    }

    #[Override]
    public function homeworkIdsWithExceptions(TenantId $tenantId): array
    {
        $tenantExceptions = $this->findByTenant($tenantId);

        return array_values(array_unique(array_map(
            static fn (HomeworkRuleException $e): string => (string) $e->homeworkId,
            $tenantExceptions,
        )));
    }
}
