<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Csrf;
use App\Core\Response;
use App\Core\Session;
use App\Services\AssignmentService;
use App\Services\PatientService;
use InvalidArgumentException;

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

    public function index(int $patientId): Response
    {
        $patient = $this->patients->find($patientId);
        return $this->view('assignments/index', [
            'pageTitle' => 'Patient Assignments',
            'pageDescription' => 'Manage current therapists and assignment history for this patient.',
            'patient' => $patient,
            'assignments' => $this->service->forPatient($patientId),
            'therapists' => $this->service->availableTherapists(),
            'csrf' => Csrf::token(),
            'message' => Session::pull('assignment_message'),
            'error' => Session::pull('assignment_error'),
            'form' => Session::pull('assignment_form'),
        ]);
    }

    public function store(int $patientId): Response
    {
        Csrf::verify((string)($_POST['_csrf'] ?? ''));
        try {
            $this->service->assign(
                $patientId,
                (int)($_POST['therapist_id'] ?? 0),
                trim((string)($_POST['role'] ?? 'supporting')),
                trim((string)($_POST['assigned_at'] ?? '')),
                trim((string)($_POST['notes'] ?? '')),
                Auth::id() ?? 0
            );
            Session::put('assignment_message', 'Patient assigned successfully.');
        } catch (InvalidArgumentException $e) {
            Session::put('assignment_error', $e->getMessage());
            Session::put('assignment_form', $_POST);
        }
        return Response::redirect('/crm/public/patients/'.$patientId.'/assignments');
    }

    public function end(int $assignmentId): Response
    {
        Csrf::verify((string)($_POST['_csrf'] ?? ''));
        try {
            $assignment = (new \App\Repositories\AssignmentRepository())->find($assignmentId);
            if ($assignment === null) throw new InvalidArgumentException('Assignment not found.');
            $this->service->end($assignmentId, trim((string)($_POST['ended_at'] ?? '')), Auth::id() ?? 0);
            Session::put('assignment_message', 'Patient assignment ended successfully.');
            return Response::redirect('/crm/public/patients/'.$assignment['patient_id'].'/assignments');
        } catch (InvalidArgumentException $e) {
            Session::put('assignment_error', $e->getMessage());
            return Response::redirect('/crm/public/');
        }
    }
}
