<?php

declare(strict_types=1);

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

use ApiPlatform\Metadata\Delete;
use App\Administration\Domain\Model\SchoolClass\ClassId;
use App\Administration\Domain\Model\Subject\SubjectId;
use App\Administration\Domain\Model\User\UserId;
use App\Scolarite\Application\Command\EndReplacement\EndReplacementHandler;
use App\Scolarite\Domain\Model\TeacherReplacement\ClassSubjectPair;
use App\Scolarite\Domain\Model\TeacherReplacement\ReplacementStatus;
use App\Scolarite\Domain\Model\TeacherReplacement\TeacherReplacement;
use App\Scolarite\Infrastructure\Api\Processor\EndTeacherReplacementProcessor;
use App\Scolarite\Infrastructure\Api\Resource\TeacherReplacementResource;
use App\Scolarite\Infrastructure\Persistence\InMemory\InMemoryTeacherReplacementRepository;
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\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Security\Core\Authorization\AccessDecision;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

final class EndTeacherReplacementProcessorTest extends TestCase
{
    private const string TENANT_ID = '550e8400-e29b-41d4-a716-446655440001';
    private const string REPLACED_TEACHER_ID = '550e8400-e29b-41d4-a716-446655440010';
    private const string REPLACEMENT_TEACHER_ID = '550e8400-e29b-41d4-a716-446655440011';
    private const string CLASS_ID = '550e8400-e29b-41d4-a716-446655440020';
    private const string SUBJECT_ID = '550e8400-e29b-41d4-a716-446655440030';
    private const string CREATED_BY_ID = '550e8400-e29b-41d4-a716-446655440099';

    private InMemoryTeacherReplacementRepository $replacementRepository;
    private TenantContext $tenantContext;
    private Clock $clock;

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

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

        $result = $processor->process(
            new TeacherReplacementResource(),
            new Delete(),
            ['id' => (string) $replacement->id],
        );

        self::assertNull($result);

        $ended = $this->replacementRepository->get($replacement->id, TenantId::fromString(self::TENANT_ID));
        self::assertSame(ReplacementStatus::ENDED, $ended->status);
        self::assertNotNull($ended->endedAt);
    }

    #[Test]
    public function itRejectsUnauthorizedAccess(): void
    {
        $replacement = $this->createAndSaveReplacement();
        $processor = $this->createProcessor(granted: false);
        $this->setTenant();

        $this->expectException(AccessDeniedHttpException::class);
        $processor->process(
            new TeacherReplacementResource(),
            new Delete(),
            ['id' => (string) $replacement->id],
        );
    }

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

        $this->expectException(UnauthorizedHttpException::class);
        $processor->process(
            new TeacherReplacementResource(),
            new Delete(),
            ['id' => (string) $replacement->id],
        );
    }

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

        $this->expectException(NotFoundHttpException::class);
        $processor->process(
            new TeacherReplacementResource(),
            new Delete(),
            ['id' => '550e8400-e29b-41d4-a716-446655440088'],
        );
    }

    #[Test]
    public function itMapsAlreadyEndedExceptionToBadRequest(): void
    {
        $replacement = $this->createAndSaveReplacement();
        $replacement->terminer(new DateTimeImmutable('2026-03-10'));
        $this->replacementRepository->save($replacement);

        $processor = $this->createProcessor(granted: true);
        $this->setTenant();

        $this->expectException(BadRequestHttpException::class);
        $processor->process(
            new TeacherReplacementResource(),
            new Delete(),
            ['id' => (string) $replacement->id],
        );
    }

    private function createAndSaveReplacement(): TeacherReplacement
    {
        $replacement = TeacherReplacement::designer(
            tenantId: TenantId::fromString(self::TENANT_ID),
            replacedTeacherId: UserId::fromString(self::REPLACED_TEACHER_ID),
            replacementTeacherId: UserId::fromString(self::REPLACEMENT_TEACHER_ID),
            startDate: new DateTimeImmutable('2026-03-01'),
            endDate: new DateTimeImmutable('2026-03-31'),
            classes: [
                new ClassSubjectPair(
                    ClassId::fromString(self::CLASS_ID),
                    SubjectId::fromString(self::SUBJECT_ID),
                ),
            ],
            reason: null,
            createdBy: UserId::fromString(self::CREATED_BY_ID),
            now: new DateTimeImmutable('2026-02-15 10:00:00'),
        );

        $this->replacementRepository->save($replacement);

        return $replacement;
    }

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

    private function createProcessor(bool $granted): EndTeacherReplacementProcessor
    {
        $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;
            }
        };

        $handler = new EndReplacementHandler(
            $this->replacementRepository,
            $this->clock,
        );

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