<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Repositories\StudentRepository;
use App\Services\RequirementService;
use App\Support\Auth;
use App\Support\Request;
use App\Support\Response;

final class StudentsController
{
    public function index(): void
    {
        $user = Auth::requireUser();
        $students = (new StudentRepository())->allForTenant((int) $user['tenant_id']);
        $requirements = new RequirementService();

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

        Response::json(['data' => $students]);
    }

    public function store(Request $request): void
    {
        $user = Auth::requireRole(['tenant_admin', 'dispatcher']);
        $student = (new StudentRepository())->create((int) $user['tenant_id'], $request->input());
        $student['progress'] = (new RequirementService())->progressForStudent((int) $student['id']);

        Response::json(['data' => $student], 201);
    }

    public function update(Request $request, array $params): void
    {
        $user = Auth::requireRole(['tenant_admin', 'dispatcher']);
        $student = (new StudentRepository())->update((int) $user['tenant_id'], (int) $params['id'], $request->input());

        if ($student === null) {
            Response::json(['message' => 'Not found'], 404);
        }

        $student['progress'] = (new RequirementService())->progressForStudent((int) $student['id']);
        Response::json(['data' => $student]);
    }

    public function updateTraining(Request $request, array $params): void
    {
        $user = Auth::requireRole(['tenant_admin', 'dispatcher']);
        $student = (new StudentRepository())->updatePriorCompletedUnits(
            (int) $user['tenant_id'],
            (int) $params['id'],
            $request->input()['rows'] ?? []
        );

        if ($student === null) {
            Response::json(['message' => 'Not found'], 404);
        }

        $student['progress'] = (new RequirementService())->progressForStudent((int) $student['id']);
        Response::json(['data' => $student]);
    }

    public function destroy(Request $request, array $params): void
    {
        $user = Auth::requireRole(['tenant_admin', 'dispatcher']);
        $deleted = (new StudentRepository())->delete((int) $user['tenant_id'], (int) $params['id']);

        if (!$deleted) {
            Response::json(['message' => 'Not found'], 404);
        }

        Response::noContent();
    }
}
