<?php

declare(strict_types=1);

namespace App\SuperAdmin\Infrastructure\Persistence\InMemory;

use App\Shared\Domain\Tenant\TenantId;
use App\SuperAdmin\Domain\Exception\EstablishmentIntrouvableException;
use App\SuperAdmin\Domain\Model\Establishment\Establishment;
use App\SuperAdmin\Domain\Model\Establishment\EstablishmentId;
use App\SuperAdmin\Domain\Repository\EstablishmentRepository;
use Override;

final class InMemoryEstablishmentRepository implements EstablishmentRepository
{
    /** @var array<string, Establishment> */
    private array $establishments = [];

    #[Override]
    public function save(Establishment $establishment): void
    {
        $this->establishments[(string) $establishment->id] = $establishment;
    }

    #[Override]
    public function get(EstablishmentId $id): Establishment
    {
        return $this->establishments[(string) $id]
            ?? throw EstablishmentIntrouvableException::avecId($id);
    }

    #[Override]
    public function findByTenantId(TenantId $tenantId): ?Establishment
    {
        foreach ($this->establishments as $establishment) {
            if ($establishment->tenantId->equals($tenantId)) {
                return $establishment;
            }
        }

        return null;
    }

    /**
     * @return Establishment[]
     */
    #[Override]
    public function findAll(): array
    {
        return array_values($this->establishments);
    }
}
