<?php

declare(strict_types=1);

namespace App\Tests\Unit\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Patch;
use App\Administration\Application\Command\UpdatePeriod\UpdatePeriodHandler;
use App\Administration\Domain\Model\AcademicYear\DefaultPeriods;
use App\Administration\Domain\Model\AcademicYear\PeriodType;
use App\Administration\Domain\Model\SchoolClass\AcademicYearId;
use App\Administration\Infrastructure\Api\Processor\UpdatePeriodProcessor;
use App\Administration\Infrastructure\Api\Resource\PeriodItem;
use App\Administration\Infrastructure\Api\Resource\PeriodResource;
use App\Administration\Infrastructure\Persistence\InMemory\InMemoryPeriodConfigurationRepository;
use App\Administration\Infrastructure\Service\CurrentAcademicYearResolver;
use App\Administration\Infrastructure\Service\NoOpGradeExistenceChecker;
use App\Shared\Domain\Clock;
use App\Shared\Domain\Tenant\TenantId;
use App\Shared\Infrastructure\Tenant\TenantConfig;
use App\Shared\Infrastructure\Tenant\TenantContext;
use App\Shared\Infrastructure\Tenant\TenantId as InfraTenantId;
use DateTimeImmutable;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecision;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

final class UpdatePeriodProcessorTest extends TestCase
{
    private const string TENANT_UUID = '550e8400-e29b-41d4-a716-446655440001';

    private InMemoryPeriodConfigurationRepository $repository;
    private TenantContext $tenantContext;
    private Clock $clock;

    protected function setUp(): void
    {
        $this->repository = new InMemoryPeriodConfigurationRepository();
        $this->tenantContext = new TenantContext();
        $this->clock = new class implements Clock {
            public function now(): DateTimeImmutable
            {
                return new DateTimeImmutable('2025-10-15 10:00:00');
            }
        };
    }

    #[Test]
    public function itRejectsInvalidAcademicYearId(): void
    {
        $processor = $this->createProcessor();
        $this->setTenant();

        $data = new PeriodResource();
        $data->startDate = '2025-09-02';
        $data->endDate = '2025-11-30';

        $this->expectException(NotFoundHttpException::class);
        $processor->process($data, new Patch(), ['academicYearId' => 'invalid', 'sequence' => 1]);
    }

    #[Test]
    public function itRejectsWhenNoPeriodsConfigured(): void
    {
        $processor = $this->createProcessor();
        $this->setTenant();

        $data = new PeriodResource();
        $data->startDate = '2025-09-02';
        $data->endDate = '2025-11-30';

        $this->expectException(NotFoundHttpException::class);
        $processor->process($data, new Patch(), ['academicYearId' => 'current', 'sequence' => 1]);
    }

    #[Test]
    public function itUpdatesPeriodDates(): void
    {
        $processor = $this->createProcessor();
        $this->setTenant();
        $this->seedPeriods();

        $data = new PeriodResource();
        $data->startDate = '2025-09-02';
        $data->endDate = '2025-11-30';

        $result = $processor->process($data, new Patch(), ['academicYearId' => 'current', 'sequence' => 1]);

        self::assertInstanceOf(PeriodResource::class, $result);
        self::assertSame('trimester', $result->type);
        self::assertCount(3, $result->periods);
        self::assertContainsOnlyInstancesOf(PeriodItem::class, $result->periods);

        // First period has updated start date
        self::assertSame('2025-09-02', $result->periods[0]->startDate);
        self::assertSame('2025-11-30', $result->periods[0]->endDate);
    }

    #[Test]
    public function itResolvesCurrentAcademicYearId(): void
    {
        $processor = $this->createProcessor();
        $this->setTenant();
        $this->seedPeriods();

        $resolver = new CurrentAcademicYearResolver($this->tenantContext, $this->clock);
        $expectedUuid = $resolver->resolve('current');

        $data = new PeriodResource();
        $data->startDate = '2025-09-02';
        $data->endDate = '2025-11-30';

        $result = $processor->process($data, new Patch(), ['academicYearId' => 'current', 'sequence' => 1]);

        self::assertSame($expectedUuid, $result->academicYearId);
    }

    #[Test]
    public function itRejectsMissingStartDate(): void
    {
        $processor = $this->createProcessor();
        $this->setTenant();
        $this->seedPeriods();

        $data = new PeriodResource();
        $data->endDate = '2025-11-30';

        $this->expectException(BadRequestHttpException::class);
        $this->expectExceptionMessage('obligatoires');
        $processor->process($data, new Patch(), ['academicYearId' => 'current', 'sequence' => 1]);
    }

    #[Test]
    public function itRejectsMissingEndDate(): void
    {
        $processor = $this->createProcessor();
        $this->setTenant();
        $this->seedPeriods();

        $data = new PeriodResource();
        $data->startDate = '2025-09-01';

        $this->expectException(BadRequestHttpException::class);
        $this->expectExceptionMessage('obligatoires');
        $processor->process($data, new Patch(), ['academicYearId' => 'current', 'sequence' => 1]);
    }

    #[Test]
    public function itRejectsOverlappingDates(): void
    {
        $processor = $this->createProcessor();
        $this->setTenant();
        $this->seedPeriods();

        $data = new PeriodResource();
        // T1 end date overlaps with T2 start date (Dec 1)
        $data->startDate = '2025-09-01';
        $data->endDate = '2025-12-15';

        $this->expectException(BadRequestHttpException::class);
        $processor->process($data, new Patch(), ['academicYearId' => 'current', 'sequence' => 1]);
    }

    private function setTenant(): void
    {
        $this->tenantContext->setCurrentTenant(new TenantConfig(
            tenantId: InfraTenantId::fromString(self::TENANT_UUID),
            subdomain: 'test',
            databaseUrl: 'sqlite:///:memory:',
        ));
    }

    private function seedPeriods(): void
    {
        $resolver = new CurrentAcademicYearResolver($this->tenantContext, $this->clock);
        $academicYearId = $resolver->resolve('current');
        self::assertNotNull($academicYearId);

        $config = DefaultPeriods::forType(PeriodType::TRIMESTER, 2025);
        $this->repository->save(
            TenantId::fromString(self::TENANT_UUID),
            AcademicYearId::fromString($academicYearId),
            $config,
        );
    }

    private function createProcessor(): UpdatePeriodProcessor
    {
        $authChecker = new class implements AuthorizationCheckerInterface {
            public function isGranted(mixed $attribute, mixed $subject = null, ?AccessDecision $accessDecision = null): bool
            {
                return true;
            }
        };

        $eventBus = new class implements MessageBusInterface {
            public function dispatch(object $message, array $stamps = []): Envelope
            {
                return new Envelope($message);
            }
        };
        $handler = new UpdatePeriodHandler($this->repository, new NoOpGradeExistenceChecker(), $this->clock, $eventBus);
        $resolver = new CurrentAcademicYearResolver($this->tenantContext, $this->clock);

        return new UpdatePeriodProcessor($handler, $this->tenantContext, $authChecker, $resolver);
    }
}
