<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Persistence\InMemory;

use App\Administration\Domain\Exception\CalendrierNonTrouveException;
use App\Administration\Domain\Model\SchoolCalendar\SchoolCalendar;
use App\Administration\Domain\Model\SchoolCalendar\SchoolCalendarRepository;
use App\Administration\Domain\Model\SchoolClass\AcademicYearId;
use App\Shared\Domain\Tenant\TenantId;
use Override;

final class InMemorySchoolCalendarRepository implements SchoolCalendarRepository
{
    /** @var array<string, SchoolCalendar> Indexé par tenant:year */
    private array $calendars = [];

    #[Override]
    public function save(SchoolCalendar $calendar): void
    {
        $this->calendars[$this->key($calendar->tenantId, $calendar->academicYearId)] = $calendar;
    }

    #[Override]
    public function findByTenantAndYear(TenantId $tenantId, AcademicYearId $academicYearId): ?SchoolCalendar
    {
        return $this->calendars[$this->key($tenantId, $academicYearId)] ?? null;
    }

    #[Override]
    public function getByTenantAndYear(TenantId $tenantId, AcademicYearId $academicYearId): SchoolCalendar
    {
        $calendar = $this->findByTenantAndYear($tenantId, $academicYearId);

        if ($calendar === null) {
            throw CalendrierNonTrouveException::pourTenantEtAnnee($tenantId, $academicYearId);
        }

        return $calendar;
    }

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