<?php

namespace App\Http\Controllers\Tenant;

use App\Domain\WhatsApp\WhatsAppManager;
use App\Http\Controllers\Controller;
use App\Http\Requests\SendWhatsAppRequest;
use App\Models\Patient;
use App\Models\WaMessage;

class WhatsAppController extends Controller
{
    public function __construct(protected WhatsAppManager $wa)
    {
    }

    /** Clinic-wide conversation log (all messages, filterable). */
    public function index()
    {
        $this->authorize('viewAny', WaMessage::class);

        return view('whatsapp.log', [
            'messages' => WaMessage::with('patient:id,full_name')
                ->when(request('status'), fn ($q, $s) => $q->where('status', $s))
                ->latest()->paginate(40)->withQueryString(),
        ]);
    }

    /** Per-patient thread. */
    public function thread(Patient $patient)
    {
        $this->authorize('view', $patient);

        return view('whatsapp.thread', [
            'patient' => $patient,
            'messages' => WaMessage::where('patient_id', $patient->id)
                ->orderBy('created_at')->get(),
        ]);
    }

    /** Manual free-text send to a patient. */
    public function send(SendWhatsAppRequest $request, Patient $patient)
    {
        $this->authorize('view', $patient);

        $this->wa->queueRaw(
            patient: $patient,
            body: $request->body,
            createdBy: $request->user()->id,
        );

        return back()->with('status', __('Message queued.'));
    }

    public function retry(WaMessage $message)
    {
        $this->authorize('retry', $message);
        $this->wa->retry($message);

        return back()->with('status', __('Message re-queued for sending.'));
    }
}
