<?php

namespace App\Http\Controllers\Care;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Models\CareUnit;
use App\Models\Visit;
use App\Services\Care\AssessmentService;
use App\Services\Care\CareFeatures;
use App\Services\Care\CarePermissions;
use App\Services\Care\NursingAssessmentService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class NursingAssessmentController extends Controller
{
    use ScopesToAccount;

    public function unitBoard(Request $request, CareUnit $careUnit, NursingAssessmentService $nursing): View
    {
        $this->authorizeAbility($request, 'nursing.assessments.view');
        $this->authorizeOwner($request, $careUnit);
        abort_unless((int) $careUnit->organization_id === (int) $this->organization($request)->id, 404);

        app(CareFeatures::class)->ensureAssessmentCatalog();

        $permissions = app(CarePermissions::class);
        $member = $this->member($request);

        return view('care.nursing.assessments-board', [
            'unit' => $careUnit->load('department.branch'),
            'templates' => $nursing->nursingTemplates(),
            'rows' => $nursing->unitBoard($careUnit, $this->ownerRef($request)),
            'canCapture' => $permissions->can($member, 'nursing.assessments.manage')
                || $permissions->can($member, 'assessments.capture')
                || $permissions->can($member, 'assessments.manage'),
            'canVitals' => $permissions->can($member, 'vitals.manage'),
            'engineEnabled' => app(CareFeatures::class)->enabled(
                $this->organization($request),
                CareFeatures::ASSESSMENTS_ENGINE,
            ),
        ]);
    }

    public function start(
        Request $request,
        CareUnit $careUnit,
        Visit $visit,
        AssessmentService $assessments,
        CareFeatures $features,
    ): RedirectResponse {
        $this->authorizeAbility($request, 'nursing.assessments.manage');
        $this->authorizeOwner($request, $careUnit);
        $this->authorizeOwner($request, $visit);
        abort_unless((int) $visit->care_unit_id === (int) $careUnit->id, 404);
        abort_unless($features->enabled($this->organization($request), CareFeatures::ASSESSMENTS_ENGINE), 404);

        $features->ensureAssessmentCatalog();

        $validated = $request->validate([
            'template_code' => ['required', 'string', 'max:100'],
        ]);

        $assessment = $assessments->start(
            $visit->patient,
            $validated['template_code'],
            $this->ownerRef($request),
            $this->member($request),
            [
                'visit' => $visit,
                'actor' => $this->actorRef($request),
            ],
        );

        return redirect()
            ->route('care.assessments.show', $assessment)
            ->with('success', 'Nursing assessment started.');
    }

    public function storeVitals(
        Request $request,
        CareUnit $careUnit,
        Visit $visit,
        NursingAssessmentService $nursing,
    ): RedirectResponse {
        $this->authorizeAbility($request, 'vitals.manage');
        $this->authorizeOwner($request, $careUnit);
        $this->authorizeOwner($request, $visit);
        abort_unless((int) $visit->care_unit_id === (int) $careUnit->id, 404);

        $validated = $request->validate([
            'bp_systolic' => ['nullable', 'integer', 'min:40', 'max:300'],
            'bp_diastolic' => ['nullable', 'integer', 'min:20', 'max:200'],
            'pulse' => ['nullable', 'integer', 'min:20', 'max:300'],
            'temperature' => ['nullable', 'numeric', 'min:30', 'max:45'],
            'spo2' => ['nullable', 'integer', 'min:50', 'max:100'],
            'respiratory_rate' => ['nullable', 'integer', 'min:4', 'max:60'],
            'notes' => ['nullable', 'string', 'max:1000'],
        ]);

        $nursing->recordVisitVitals(
            $visit,
            $this->ownerRef($request),
            $this->actorRef($request),
            $validated,
        );

        return redirect()
            ->route('care.care-units.assessments', $careUnit)
            ->with('success', 'Ward vitals recorded.');
    }
}
