<?php

namespace App\Http\Controllers\Tenant;

use App\Domain\Files\PatientFileService;
use App\Http\Controllers\Controller;
use App\Http\Requests\PatientFileRequest;
use App\Models\Patient;
use App\Models\PatientFile;
use Illuminate\Support\Facades\Storage;

class PatientFileController extends Controller
{
    public function __construct(protected PatientFileService $files)
    {
    }

    /** Gallery: before/after pairs, X-rays, other files. */
    public function index(Patient $patient)
    {
        $this->authorize('view', $patient);
        abort_unless(auth()->user()->can('files.view'), 403);

        $all = PatientFile::where('patient_id', $patient->id)->latest()->get();

        return view('patients.files', [
            'patient' => $patient,
            'befores' => $all->where('type', 'photo_before')->values(),
            'afters' => $all->where('type', 'photo_after')->values(),
            'xrays' => $all->where('type', 'xray')->values(),
            'others' => $all->where('type', 'other')->values(),
            'plans' => \App\Models\TreatmentPlan::where('patient_id', $patient->id)
                ->latest()->get(['id', 'title']),
        ]);
    }

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

        $this->files->store(
            patient: $patient,
            upload: $request->file('file'),
            type: $request->type,
            teeth: $request->teeth,
            caption: $request->caption,
            treatmentPlanId: $request->integer('treatment_plan_id') ?: null,
            appointmentId: $request->integer('appointment_id') ?: null,
            uploadedBy: $request->user()->id,
        );

        return back()->with('status', __('File uploaded.'));
    }

    /** Stream the binary (PHI: private disk, tenant-checked by the global scope). */
    public function serve(PatientFile $file, string $variant = 'full')
    {
        $this->authorize('view', $file);

        $path = $variant === 'thumb' && $file->thumb_path ? $file->thumb_path : $file->path;
        abort_unless(Storage::disk(PatientFileService::DISK)->exists($path), 404);

        return Storage::disk(PatientFileService::DISK)->response($path, $file->original_name);
    }

    public function pair(Patient $patient, PatientFile $before, PatientFile $after)
    {
        $this->authorize('update', $after);
        abort_unless($before->patient_id === $patient->id && $after->patient_id === $patient->id, 404);

        $this->files->pair($before, $after);

        return back()->with('status', __('Photos paired.'));
    }

    public function destroy(Patient $patient, PatientFile $file)
    {
        abort_unless($file->patient_id === $patient->id, 404);
        $this->authorize('delete', $file);

        $this->files->delete($file);

        return back()->with('status', __('File deleted.'));
    }
}
