<?php

declare(strict_types=1);

namespace App\Tests\Unit\Scolarite\Application\Query\GetReplacedClassesForTeacher;

use App\Administration\Domain\Model\SchoolClass\AcademicYearId;
use App\Administration\Domain\Model\SchoolClass\ClassId;
use App\Administration\Domain\Model\SchoolClass\ClassName;
use App\Administration\Domain\Model\SchoolClass\ClassStatus;
use App\Administration\Domain\Model\SchoolClass\SchoolClass;
use App\Administration\Domain\Model\SchoolClass\SchoolId;
use App\Administration\Domain\Model\Subject\Subject;
use App\Administration\Domain\Model\Subject\SubjectCode;
use App\Administration\Domain\Model\Subject\SubjectId;
use App\Administration\Domain\Model\Subject\SubjectName;
use App\Administration\Domain\Model\Subject\SubjectStatus;
use App\Administration\Domain\Model\User\UserId;
use App\Administration\Infrastructure\Persistence\InMemory\InMemoryClassRepository;
use App\Administration\Infrastructure\Persistence\InMemory\InMemorySubjectRepository;
use App\Scolarite\Application\Query\GetReplacedClassesForTeacher\GetReplacedClassesForTeacherHandler;
use App\Scolarite\Application\Query\GetReplacedClassesForTeacher\GetReplacedClassesForTeacherQuery;
use App\Scolarite\Application\Query\GetReplacedClassesForTeacher\ReplacedClassDto;
use App\Scolarite\Domain\Model\TeacherReplacement\ClassSubjectPair;
use App\Scolarite\Domain\Model\TeacherReplacement\TeacherReplacement;
use App\Scolarite\Infrastructure\Persistence\InMemory\InMemoryTeacherReplacementRepository;
use App\Shared\Domain\Clock;
use App\Shared\Domain\Tenant\TenantId;
use DateTimeImmutable;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;

final class GetReplacedClassesForTeacherHandlerTest 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 OTHER_TEACHER_ID = '550e8400-e29b-41d4-a716-446655440012';
    private const string CLASS_ID_1 = '550e8400-e29b-41d4-a716-446655440020';
    private const string SUBJECT_ID_1 = '550e8400-e29b-41d4-a716-446655440030';
    private const string CLASS_ID_2 = '550e8400-e29b-41d4-a716-446655440021';
    private const string SUBJECT_ID_2 = '550e8400-e29b-41d4-a716-446655440031';
    private const string CREATED_BY_ID = '550e8400-e29b-41d4-a716-446655440099';
    private const string SCHOOL_ID = '550e8400-e29b-41d4-a716-446655440040';
    private const string ACADEMIC_YEAR_ID = '550e8400-e29b-41d4-a716-446655440041';

    private InMemoryTeacherReplacementRepository $repository;
    private InMemoryClassRepository $classRepository;
    private InMemorySubjectRepository $subjectRepository;
    private DateTimeImmutable $now;

    protected function setUp(): void
    {
        $this->repository = new InMemoryTeacherReplacementRepository();
        $this->classRepository = new InMemoryClassRepository();
        $this->subjectRepository = new InMemorySubjectRepository();
        $this->now = new DateTimeImmutable('2026-03-15 10:00:00');

        $this->seedClassesAndSubjects();
    }

    #[Test]
    public function itReturnsReplacedClassesForTeacher(): void
    {
        $this->saveReplacement();

        $handler = $this->createHandler();
        $result = $handler(new GetReplacedClassesForTeacherQuery(
            replacementTeacherId: self::REPLACEMENT_TEACHER_ID,
            tenantId: self::TENANT_ID,
        ));

        self::assertCount(1, $result);
        self::assertContainsOnlyInstancesOf(ReplacedClassDto::class, $result);
    }

    #[Test]
    public function itReturnsEmptyWhenNoReplacements(): void
    {
        $handler = $this->createHandler();
        $result = $handler(new GetReplacedClassesForTeacherQuery(
            replacementTeacherId: self::REPLACEMENT_TEACHER_ID,
            tenantId: self::TENANT_ID,
        ));

        self::assertSame([], $result);
    }

    #[Test]
    public function itFlattensClassSubjectPairs(): void
    {
        $this->saveReplacementWithMultipleClasses();

        $handler = $this->createHandler();
        $result = $handler(new GetReplacedClassesForTeacherQuery(
            replacementTeacherId: self::REPLACEMENT_TEACHER_ID,
            tenantId: self::TENANT_ID,
        ));

        self::assertCount(2, $result);

        $classIds = array_map(static fn (ReplacedClassDto $dto) => $dto->classId, $result);
        self::assertContains(self::CLASS_ID_1, $classIds);
        self::assertContains(self::CLASS_ID_2, $classIds);

        $subjectIds = array_map(static fn (ReplacedClassDto $dto) => $dto->subjectId, $result);
        self::assertContains(self::SUBJECT_ID_1, $subjectIds);
        self::assertContains(self::SUBJECT_ID_2, $subjectIds);
    }

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

        $handler = $this->createHandler();
        $result = $handler(new GetReplacedClassesForTeacherQuery(
            replacementTeacherId: self::REPLACEMENT_TEACHER_ID,
            tenantId: self::TENANT_ID,
        ));

        self::assertSame([], $result);
    }

    #[Test]
    public function itDoesNotReturnReplacementsForOtherTeachers(): void
    {
        $this->saveReplacement();

        $handler = $this->createHandler();
        $result = $handler(new GetReplacedClassesForTeacherQuery(
            replacementTeacherId: self::OTHER_TEACHER_ID,
            tenantId: self::TENANT_ID,
        ));

        self::assertSame([], $result);
    }

    #[Test]
    public function itMapsDtoFieldsCorrectly(): void
    {
        $replacement = $this->saveReplacement();

        $handler = $this->createHandler();
        $result = $handler(new GetReplacedClassesForTeacherQuery(
            replacementTeacherId: self::REPLACEMENT_TEACHER_ID,
            tenantId: self::TENANT_ID,
        ));

        self::assertCount(1, $result);

        $dto = $result[0];
        self::assertSame((string) $replacement->id, $dto->replacementId);
        self::assertSame(self::REPLACED_TEACHER_ID, $dto->replacedTeacherId);
        self::assertSame(self::CLASS_ID_1, $dto->classId);
        self::assertSame(self::SUBJECT_ID_1, $dto->subjectId);
        self::assertSame('6ème A', $dto->className);
        self::assertSame('Mathématiques', $dto->subjectName);
        self::assertEquals(new DateTimeImmutable('2026-03-01'), $dto->startDate);
        self::assertEquals(new DateTimeImmutable('2026-03-31'), $dto->endDate);
    }

    private function saveReplacement(): 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_1),
                    SubjectId::fromString(self::SUBJECT_ID_1),
                ),
            ],
            reason: null,
            createdBy: UserId::fromString(self::CREATED_BY_ID),
            now: new DateTimeImmutable('2026-02-15 10:00:00'),
        );

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

        return $replacement;
    }

    private function saveReplacementWithMultipleClasses(): 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_1),
                    SubjectId::fromString(self::SUBJECT_ID_1),
                ),
                new ClassSubjectPair(
                    ClassId::fromString(self::CLASS_ID_2),
                    SubjectId::fromString(self::SUBJECT_ID_2),
                ),
            ],
            reason: null,
            createdBy: UserId::fromString(self::CREATED_BY_ID),
            now: new DateTimeImmutable('2026-02-15 10:00:00'),
        );

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

        return $replacement;
    }

    private function seedClassesAndSubjects(): void
    {
        $tenantId = TenantId::fromString(self::TENANT_ID);
        $schoolId = SchoolId::fromString(self::SCHOOL_ID);
        $academicYearId = AcademicYearId::fromString(self::ACADEMIC_YEAR_ID);
        $now = new DateTimeImmutable('2026-01-01');

        $class1 = SchoolClass::reconstitute(
            ClassId::fromString(self::CLASS_ID_1), $tenantId, $schoolId, $academicYearId,
            new ClassName('6ème A'), null, null, ClassStatus::ACTIVE, null, $now, $now, null,
        );
        $this->classRepository->save($class1);

        $class2 = SchoolClass::reconstitute(
            ClassId::fromString(self::CLASS_ID_2), $tenantId, $schoolId, $academicYearId,
            new ClassName('5ème B'), null, null, ClassStatus::ACTIVE, null, $now, $now, null,
        );
        $this->classRepository->save($class2);

        $subject1 = Subject::reconstitute(
            SubjectId::fromString(self::SUBJECT_ID_1), $tenantId, $schoolId,
            new SubjectName('Mathématiques'), new SubjectCode('MATH'), null,
            SubjectStatus::ACTIVE,
            null, $now, $now, null,
        );
        $this->subjectRepository->save($subject1);

        $subject2 = Subject::reconstitute(
            SubjectId::fromString(self::SUBJECT_ID_2), $tenantId, $schoolId,
            new SubjectName('Français'), new SubjectCode('FR'), null,
            SubjectStatus::ACTIVE,
            null, $now, $now, null,
        );
        $this->subjectRepository->save($subject2);
    }

    private function createHandler(): GetReplacedClassesForTeacherHandler
    {
        $now = $this->now;
        $clock = new class($now) implements Clock {
            public function __construct(private readonly DateTimeImmutable $now)
            {
            }

            public function now(): DateTimeImmutable
            {
                return $this->now;
            }
        };

        return new GetReplacedClassesForTeacherHandler(
            $this->repository,
            $this->classRepository,
            $this->subjectRepository,
            $clock,
        );
    }
}
