<?php

declare(strict_types=1);

namespace App\Scolarite\Application\Query\GetChildrenHomework;

use App\Scolarite\Application\Port\ParentChildrenReader;
use App\Scolarite\Application\Port\ScheduleDisplayReader;
use App\Scolarite\Application\Port\StudentClassReader;
use App\Scolarite\Application\Query\GetStudentHomework\StudentHomeworkDetailDto;
use App\Scolarite\Domain\Model\Homework\HomeworkId;
use App\Scolarite\Domain\Repository\HomeworkAttachmentRepository;
use App\Scolarite\Domain\Repository\HomeworkRepository;
use App\Shared\Domain\Tenant\TenantId;

final readonly class GetChildrenHomeworkDetailHandler
{
    public function __construct(
        private ParentChildrenReader $parentChildrenReader,
        private StudentClassReader $studentClassReader,
        private HomeworkRepository $homeworkRepository,
        private HomeworkAttachmentRepository $attachmentRepository,
        private ScheduleDisplayReader $displayReader,
    ) {
    }

    public function __invoke(string $parentId, string $tenantId, string $homeworkId): ?StudentHomeworkDetailDto
    {
        $tid = TenantId::fromString($tenantId);

        $homework = $this->homeworkRepository->findById(HomeworkId::fromString($homeworkId), $tid);

        if ($homework === null) {
            return null;
        }

        if (!$this->parentHasChildInClass($parentId, $tid, (string) $homework->classId)) {
            return null;
        }

        $attachments = $this->attachmentRepository->findByHomeworkId($homework->id);

        $subjects = $this->displayReader->subjectDisplay($tenantId, (string) $homework->subjectId);
        $teacherNames = $this->displayReader->teacherNames($tenantId, (string) $homework->teacherId);

        return StudentHomeworkDetailDto::fromDomain(
            $homework,
            $subjects[(string) $homework->subjectId]['name'] ?? '',
            $subjects[(string) $homework->subjectId]['color'] ?? null,
            $teacherNames[(string) $homework->teacherId] ?? '',
            $attachments,
        );
    }

    private function parentHasChildInClass(string $parentId, TenantId $tenantId, string $homeworkClassId): bool
    {
        $children = $this->parentChildrenReader->childrenOf($parentId, $tenantId);

        foreach ($children as $child) {
            $classId = $this->studentClassReader->currentClassId($child['studentId'], $tenantId);

            if ($classId === $homeworkClassId) {
                return true;
            }
        }

        return false;
    }
}
