<?php

namespace Modules\DermatologyClinic\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\ClinicCore\Entities\ClcPatient;
use Modules\DermatologyClinic\Entities\DermaScore;

/**
 * AJAX endpoints for dermatology severity scores (PASI / EASI / DLQI / IGA).
 * Business-scoped, gated by derma.scores.manage. Rendered into ClinicCore's
 * shared patient screens by the DermatologySpecialtyDriver fragment.
 */
class DermaScoreController extends Controller
{
    private function biz()
    {
        return session('user.business_id');
    }

    private function guardPatient($patientId): ClcPatient
    {
        if (! auth()->user() || ! auth()->user()->can('derma.scores.manage')) {
            abort(403, 'Unauthorized action.');
        }
        return ClcPatient::where('business_id', $this->biz())->findOrFail($patientId);
    }

    /** Record a new severity score. */
    public function store(Request $request, $patientId)
    {
        $patient = $this->guardPatient($patientId);

        $data = $request->validate([
            'score_type'     => 'required|string|in:' . implode(',', array_keys(DermaScore::SCORE_TYPES)),
            'value'          => 'required|numeric|min:0|max:999',
            'appointment_id' => 'nullable|integer',
        ]);

        $score = DermaScore::create([
            'business_id'    => $this->biz(),
            'patient_id'     => $patient->id,
            'appointment_id' => $data['appointment_id'] ?? null,
            'score_type'     => $data['score_type'],
            'value'          => $data['value'],
            'recorded_by'    => auth()->id(),
            'recorded_at'    => now(),
        ]);

        return response()->json([
            'success' => true,
            'score'   => [
                'id'          => $score->id,
                'score_type'  => $score->score_type,
                'label'       => $score->label(),
                'value'       => $score->value,
                'recorded_at' => optional($score->recorded_at)->format('Y-m-d'),
            ],
            'msg' => 'Score recorded.',
        ]);
    }

    /** Delete a score. */
    public function destroy($patientId, $scoreId)
    {
        $patient = $this->guardPatient($patientId);

        $score = DermaScore::where('business_id', $this->biz())
            ->where('patient_id', $patient->id)->findOrFail($scoreId);
        $score->delete();

        return response()->json(['success' => true, 'msg' => 'Score deleted.']);
    }
}
