<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Persistence\InMemory;

use App\Administration\Domain\Exception\SchoolBrandingNotFoundException;
use App\Administration\Domain\Model\SchoolBranding\SchoolBranding;
use App\Administration\Domain\Model\SchoolClass\SchoolId;
use App\Administration\Domain\Repository\SchoolBrandingRepository;
use App\Shared\Domain\Tenant\TenantId;
use Override;

final class InMemorySchoolBrandingRepository implements SchoolBrandingRepository
{
    /** @var array<string, SchoolBranding> Indexed by tenant:school */
    private array $byKey = [];

    #[Override]
    public function save(SchoolBranding $branding): void
    {
        $this->byKey[$this->key($branding->schoolId, $branding->tenantId)] = $branding;
    }

    #[Override]
    public function get(SchoolId $schoolId, TenantId $tenantId): SchoolBranding
    {
        $branding = $this->findBySchoolId($schoolId, $tenantId);

        if ($branding === null) {
            throw SchoolBrandingNotFoundException::pourEcole($schoolId);
        }

        return $branding;
    }

    #[Override]
    public function findBySchoolId(SchoolId $schoolId, TenantId $tenantId): ?SchoolBranding
    {
        return $this->byKey[$this->key($schoolId, $tenantId)] ?? null;
    }

    private function key(SchoolId $schoolId, TenantId $tenantId): string
    {
        return $tenantId . ':' . $schoolId;
    }
}
