<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Persistence\InMemory;

use App\Administration\Domain\Model\User\UserId;
use App\Scolarite\Domain\Model\Grade\AppreciationTemplate;
use App\Scolarite\Domain\Model\Grade\AppreciationTemplateId;
use App\Scolarite\Domain\Repository\AppreciationTemplateRepository;
use App\Shared\Domain\Tenant\TenantId;

use function array_filter;
use function array_values;

use Override;

final class InMemoryAppreciationTemplateRepository implements AppreciationTemplateRepository
{
    /** @var array<string, AppreciationTemplate> */
    private array $byId = [];

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

    #[Override]
    public function findById(AppreciationTemplateId $id, TenantId $tenantId): ?AppreciationTemplate
    {
        $template = $this->byId[(string) $id] ?? null;

        if ($template === null || (string) $template->tenantId !== (string) $tenantId) {
            return null;
        }

        return $template;
    }

    #[Override]
    public function findByTeacher(UserId $teacherId, TenantId $tenantId): array
    {
        return array_values(array_filter(
            $this->byId,
            static fn (AppreciationTemplate $t): bool => (string) $t->teacherId === (string) $teacherId
                && (string) $t->tenantId === (string) $tenantId,
        ));
    }

    #[Override]
    public function delete(AppreciationTemplateId $id, TenantId $tenantId): void
    {
        $template = $this->byId[(string) $id] ?? null;

        if ($template !== null && (string) $template->tenantId === (string) $tenantId) {
            unset($this->byId[(string) $id]);
        }
    }
}
