<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Services\Settings\SchoolCalendar\SchoolCalendarContextService;
use App\Services\Settings\SchoolCalendar\SchoolCalendarFormatterService;
use App\Services\Settings\SchoolCalendar\SchoolCalendarMeetingService;
use App\Services\Settings\SchoolCalendar\SchoolCalendarQueryService;
use Illuminate\Contracts\View\View;

class TeacherCalendarPageController extends Controller
{
    public function __construct(
        private SchoolCalendarContextService $contextService,
        private SchoolCalendarQueryService $queryService,
        private SchoolCalendarMeetingService $meetingService,
        private SchoolCalendarFormatterService $formatterService,
    ) {
    }

    public function show(): View
    {
        $schoolYear = $this->contextService->defaultSchoolYear();
        $events = $this->queryService
            ->filterEventsForAudience(
                $this->queryService->listEvents([
                    'school_year' => $schoolYear,
                ]),
                'teacher',
            )
            ->map(fn ($event) => $this->formatterService->formatEvent($event, 'teacher'))
            ->values()
            ->all();

        foreach ($this->meetingService->listMeetings($schoolYear, 'teacher', null) as $meeting) {
            $events[] = $this->formatterService->formatMeetingEvent($meeting, 'teacher');
        }

        usort($events, function (array $left, array $right): int {
            return strcmp((string) ($left['start'] ?? ''), (string) ($right['start'] ?? ''));
        });

        return view('teacher.calendar', [
            'events' => $events,
            'schoolYear' => $schoolYear,
            'defaultSemester' => $this->contextService->defaultSemester(),
        ]);
    }
}
