<?php

declare(strict_types=1);

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

use ApiPlatform\Metadata\Put;
use App\Administration\Application\Command\ConfigurePeriods\ConfigurePeriodsHandler;
use App\Administration\Infrastructure\Api\Processor\ConfigurePeriodsProcessor;
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\Shared\Domain\Clock;
use App\Shared\Infrastructure\Tenant\TenantConfig;
use App\Shared\Infrastructure\Tenant\TenantContext;
use App\Shared\Infrastructure\Tenant\TenantId;
use DateTimeImmutable;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
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 ConfigurePeriodsProcessorTest 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 itRejectsUnauthorizedAccess(): void
    {
        $processor = $this->createProcessor(granted: false);
        $this->setTenant();

        $data = new PeriodResource();
        $data->periodType = 'trimester';

        $this->expectException(AccessDeniedHttpException::class);
        $processor->process($data, new Put(), ['academicYearId' => 'current']);
    }

    #[Test]
    public function itRejectsRequestWithoutTenant(): void
    {
        $processor = $this->createProcessor(granted: true);

        $data = new PeriodResource();
        $data->periodType = 'trimester';

        $this->expectException(UnauthorizedHttpException::class);
        $processor->process($data, new Put(), ['academicYearId' => 'current']);
    }

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

        $data = new PeriodResource();
        $data->periodType = 'trimester';

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

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

        $data = new PeriodResource();
        $data->periodType = 'trimester';
        $data->startYear = 2025;

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

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

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

        $data = new PeriodResource();
        $data->periodType = 'semester';
        $data->startYear = 2025;

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

        self::assertSame('semester', $result->type);
        self::assertCount(2, $result->periods);
    }

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

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

        $data = new PeriodResource();
        $data->periodType = 'trimester';
        $data->startYear = 2025;

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

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

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

        $data = new PeriodResource();
        $data->periodType = 'trimester';
        $data->startYear = 2026;

        $result = $processor->process($data, new Put(), ['academicYearId' => 'next']);

        self::assertSame('trimester', $result->type);
        self::assertCount(3, $result->periods);
    }

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

    private function createProcessor(bool $granted): ConfigurePeriodsProcessor
    {
        $authChecker = new class($granted) implements AuthorizationCheckerInterface {
            public function __construct(private readonly bool $granted)
            {
            }

            public function isGranted(mixed $attribute, mixed $subject = null, ?AccessDecision $accessDecision = null): bool
            {
                return $this->granted;
            }
        };

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

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