<?php

namespace App\Http\Controllers\Tenant;

use App\Domain\Clinical\Fdi;
use App\Domain\Clinical\ToothChartService;
use App\Http\Controllers\Controller;
use App\Http\Requests\ToothRecordRequest;
use App\Models\Patient;
use App\Models\ToothRecord;

class ToothChartController extends Controller
{
    public function __construct(protected ToothChartService $chart)
    {
    }

    /** The dental chart screen — the product centerpiece. */
    public function show(Patient $patient)
    {
        $this->authorize('view', $patient);
        abort_unless(auth()->user()->can('chart.view'), 403);

        return view('patients.chart', [
            'patient' => $patient,
            'chart' => $this->chart->chartFor($patient),
            'upperArch' => Fdi::upperArch(),
            'lowerArch' => Fdi::lowerArch(),
            'conditions' => config('dental.conditions'),
            'surfaces' => config('dental.surfaces'),
        ]);
    }

    /** JSON chart (also used to refresh after a record is added). */
    public function data(Patient $patient)
    {
        $this->authorize('view', $patient);
        abort_unless(auth()->user()->can('chart.view'), 403);

        return response()->json(['data' => $this->chart->chartFor($patient)]);
    }

    public function store(ToothRecordRequest $request, Patient $patient)
    {
        $this->authorize('view', $patient);

        $record = $this->chart->record(
            patient: $patient,
            tooth: (int) $request->tooth,
            condition: $request->condition,
            state: $request->enum('state', \App\Enums\ToothState::class),
            surfaces: $request->surfaces,
            note: $request->note,
            recordedBy: $request->user()->id,
        );

        return $request->wantsJson()
            ? response()->json(['data' => $this->chart->present($record)], 201)
            : back()->with('status', __('Finding recorded.'));
    }

    public function destroy(Patient $patient, ToothRecord $record)
    {
        abort_unless($record->patient_id === $patient->id, 404);
        $this->authorize('delete', $record);
        abort_if($record->treatment_plan_item_id !== null, 422,
            __('Records created by treatment plans cannot be deleted directly.'));

        $record->delete();

        return request()->wantsJson()
            ? response()->json(['data' => ['deleted' => true]])
            : back()->with('status', __('Record deleted.'));
    }
}
