<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Response;
use App\Services\AssignmentService;
use App\Services\PatientService;
use RuntimeException;

final class PatientAccessController extends Controller
{
    public function __construct(private ?PatientService $patients=null, private ?AssignmentService $assignments=null)
    {
        $this->patients ??= new PatientService();
        $this->assignments ??= new AssignmentService();
    }

    public function show(int $id): Response
    {
        $userId = Auth::id() ?? 0;
        $patient = $this->patients->find($id);
        if (Auth::hasRole('THERAPIST')) {
            if (!$this->assignments->canTherapistAccessPatient($userId, $id)) {
                throw new RuntimeException('You do not have permission to access this patient.', 403);
            }
        } elseif (!Auth::hasPermission('patients.view')) {
            throw new RuntimeException('You do not have permission to access this patient.', 403);
        }
        return $this->view('patients/show', [
            'pageTitle' => 'Patient Record',
            'pageDescription' => 'Patient demographics and current care-team assignments.',
            'patient' => $patient,
            'assignments' => $this->assignments->forPatient($id),
        ]);
    }
}
