<?php

namespace Modules\PortalApi\Http\Controllers\Api;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Modules\PortalApi\Entities\PortalOwner;
use Modules\VetClinic\Entities\VcDoctor;
use Modules\VetClinic\Entities\VcPet;

class DoctorController extends Controller
{
    /** List doctors available to this clinic for the doctor-picker. */
    public function index(Request $request): JsonResponse
    {
        /** @var PortalOwner $owner */
        $owner = $request->attributes->get('portal_owner');

        $doctors = VcDoctor::where('business_id', $owner->business_id)
            ->where(function ($q) { $q->where('status', 'active')->orWhere('status', 1); })
            ->orderBy('name')
            ->get(['id', 'name', 'specialization', 'color']);

        return response()->json($doctors->map(fn ($d) => [
            'id'             => $d->id,
            'name'           => $d->name,
            'specialization' => $d->specialization,
            'color'          => $d->color,
        ])->all());
    }

    /**
     * Change the preferred doctor for a pet.
     *
     * Writes the new value to vc_pets.preferred_doctor_id immediately so the
     * owner sees it right away, AND records a vc_doctor_change_requests
     * row with scope='pet' and status='approved' so the clinic's reports
     * track the change history (current_doctor_id → requested_doctor_id).
     *
     * If the clinic later wants approval-first instead of immediate, flip
     * VC_PORTAL_DOCTOR_CHANGE_REQUIRES_APPROVAL=true in .env.
     */
    public function setPreferredDoctor(Request $request, int $petId): JsonResponse
    {
        /** @var PortalOwner $owner */
        $owner = $request->attributes->get('portal_owner');

        $data = $request->validate([
            'doctor_id' => 'nullable|integer',
            'reason'    => 'nullable|string|max:191',
        ]);

        // Scope: only owner's own pets
        $pet = VcPet::where('business_id', $owner->business_id)
            ->where('contact_id', $owner->contact_id)
            ->where('id', $petId)
            ->first();
        if (! $pet) {
            return response()->json(['message' => 'Pet not found or not yours.'], 404);
        }

        // Validate the new doctor belongs to this business
        if ($data['doctor_id']) {
            $exists = VcDoctor::where('business_id', $owner->business_id)
                ->where('id', $data['doctor_id'])
                ->exists();
            if (! $exists) {
                return response()->json(['message' => 'Doctor not available at this clinic.'], 422);
            }
        }

        $previousDoctorId = $pet->preferred_doctor_id;
        $requiresApproval = (bool) env('VC_PORTAL_DOCTOR_CHANGE_REQUIRES_APPROVAL', false);

        return DB::transaction(function () use ($pet, $owner, $data, $previousDoctorId, $requiresApproval) {
            // Always record the request in the existing log table so reports
            // can show "owner switched X → Y on date Z, reason: ...".
            // appointment_id = 0 → not tied to a specific appointment
            // (the ERP-side change-request flow uses the same convention
            // when scope is 'pet' or 'all').
            $req = DB::table('vc_doctor_change_requests')->insertGetId([
                'business_id'           => $owner->business_id,
                'appointment_id'        => 0,
                'pet_id'                => $pet->id,
                'contact_id'            => $owner->contact_id,
                'requested_by'          => 0,
                'current_doctor_id'     => $previousDoctorId ?? 0,
                'requested_doctor_id'   => $data['doctor_id'] ?? 0,
                'scope'                 => 'pet',
                'reason'                => $data['reason'] ?? 'Changed by pet owner via portal',
                'status'                => $requiresApproval ? 'pending' : 'approved',
                'reviewed_by'           => null,
                'reviewed_at'           => $requiresApproval ? null : now(),
                'review_notes'          => null,
                'consumed_at'           => null,
                'created_at'            => now(),
                'updated_at'            => now(),
            ]);

            // Apply the change immediately unless approval is required.
            if (! $requiresApproval) {
                $pet->preferred_doctor_id = $data['doctor_id'];
                $pet->save();
            }

            $newDoctor = $data['doctor_id'] ? VcDoctor::find($data['doctor_id']) : null;
            $oldDoctor = $previousDoctorId ? VcDoctor::find($previousDoctorId) : null;

            return response()->json([
                'request_id'        => $req,
                'status'            => $requiresApproval ? 'pending' : 'approved',
                'preferred_doctor'  => $newDoctor ? ['id' => $newDoctor->id, 'name' => $newDoctor->name] : null,
                'previous_doctor'   => $oldDoctor ? ['id' => $oldDoctor->id, 'name' => $oldDoctor->name] : null,
            ]);
        });
    }
}
