<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Repositories\AppointmentRepository;
use App\Repositories\InstructorRepository;
use App\Repositories\ReferenceDataRepository;
use App\Repositories\StudentRepository;
use App\Repositories\TenantRepository;
use App\Repositories\UserRepository;
use App\Services\RequirementService;
use App\Services\HolidayService;
use App\Services\SunTimesService;
use App\Support\Auth;
use App\Support\Request;
use App\Support\Response;

final class BootstrapController
{
    public function __invoke(Request $request): void
    {
        $user = Auth::requireUser();
        unset($user['password_hash']);

        $payload = ['session' => ['user' => $user]];

        if ($user['role'] === 'superadmin') {
            $payload['tenants'] = (new TenantRepository())->all();
            $payload['users'] = (new UserRepository())->allUsers();
            Response::json($payload);
        }

        $tenantId = (int) $user['tenant_id'];
        $studentRepository = new StudentRepository();
        $students = $studentRepository->allForTenant($tenantId);
        $requirementService = new RequirementService();

        foreach ($students as &$student) {
            $student['progress'] = $requirementService->progressForStudent((int) $student['id']);
        }

        $payload['tenant'] = (new TenantRepository())->find($tenantId);
        $payload['students'] = $students;
        $payload['templates'] = (new ReferenceDataRepository())->templates($tenantId);
        $payload['lessonTypes'] = (new ReferenceDataRepository())->lessonTypes($tenantId);
        $payload['instructors'] = (new InstructorRepository())->allForTenant($tenantId);
        $payload['users'] = $user['role'] === 'tenant_admin'
            ? (new UserRepository())->allForTenant($tenantId)
            : [];
        $instructorId = null;
        if ($user['role'] === 'instructor') {
            $instructor = (new InstructorRepository())->findByUserId($tenantId, (int) $user['id']);
            $instructorId = $instructor ? (int) $instructor['id'] : null;
        }

        $from = $request->query('from', gmdate('Y-m-d\T00:00:00\Z', strtotime('monday this week')));
        $to = $request->query('to', gmdate('Y-m-d\T00:00:00\Z', strtotime('+7 day', strtotime($from))));
        $payload['sunTimes'] = (new SunTimesService())->forRange($payload['tenant'], (string) $from, (string) $to);
        $payload['dayMeta'] = (new HolidayService())->forRange($payload['tenant'], (string) $from, (string) $to);
        $payload['appointments'] = (new AppointmentRepository())->listForTenant(
            $tenantId,
            (string) $from,
            (string) $to,
            $instructorId
        );
        $payload['nextAppointment'] = (new AppointmentRepository())->nextForTenant(
            $tenantId,
            gmdate(DATE_ATOM),
            $instructorId
        );

        Response::json($payload);
    }
}
