<?php

namespace Mtc\Plugins\WeightVerification\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Mtc\Core\Admin\User;
use Mtc\Core\Permissions;
use Mtc\Plugins\WeightVerification\Src\Models\WeightVerification;
use Mtc\Plugins\WeightVerification\Src\WeightVerificationService;

class WeightVerificationAdminController extends Controller
{
    private WeightVerificationService $service;

    public function __construct(WeightVerificationService $service)
    {
        $this->service = $service;
    }

    /**
     * Prescriber requests new photos for an order. Re-opens the patient tab
     * and notifies them via the existing messaging system.
     */
    public function requestResubmission(Request $request): JsonResponse
    {
        // Mirror the approve path (orderItemCanBeApproved): only a prescriber /
        // doctor reviewer may re-open a verification and message the patient.
        if (!Permissions::can(Permissions::REVIEW_DOCTOR_ORDERS)) {
            return response()->json([
                'error' => 'You do not have permission to request weight verification resubmission.',
            ], 403);
        }

        $verification = $this->service->forOrder((int) $request->input('order_id'));

        if (empty($verification)) {
            return response()->json([
                'error' => 'No weight verification found for this order.',
            ], 404);
        }

        $message = trim((string) $request->input('message'));
        if ($message === '') {
            $message = (string) config('weight_verification.default_resubmission_message');
        }

        $this->service->requestResubmission($verification, User::getAdminUser(), $message);

        return response()->json([
            'success' => 1,
            'status' => WeightVerification::STATUS_RESUBMIT_REQUIRED,
        ]);
    }
}
