<?php

namespace Modules\ClinicLab\Http\Controllers;

use Illuminate\Routing\Controller;
use Modules\ClinicLab\Entities\CllResultReview;
use Modules\ClinicLab\Entities\Services\ResultReviewService;
use Modules\LabCore\Entities\LabTestSession;

/**
 * Result validation workflow — /clinic-lab/reviews.
 * Listing lazily creates a pending review per session; review needs
 * cliniclab.result.review, verify needs cliniclab.result.verify. VERIFY closes
 * the critical-value / alert / notify / order-write-back loop.
 */
class CllReviewController extends Controller
{
    protected function bizId()
    {
        return request()->session()->get('user.business_id');
    }

    protected function guardReview(): void
    {
        $u = auth()->user();
        if (! $u || ! ($u->can('cliniclab.result.review') || $u->can('cliniclab.result.verify'))) {
            abort(403, 'Unauthorized action.');
        }
    }

    protected function guardVerify(): void
    {
        if (! auth()->user() || ! auth()->user()->can('cliniclab.result.verify')) {
            abort(403, 'Unauthorized action.');
        }
    }

    public function index(ResultReviewService $service)
    {
        $this->guardReview();
        $bizId = $this->bizId();

        $sessions = LabTestSession::with('results')
            ->where('business_id', $bizId)
            ->orderByDesc('test_date')->orderByDesc('test_time')
            ->limit(150)->get();

        $reviews = $service->ensureReviews((int) $bizId, $sessions);

        // Pre-evaluate so the listing can show a critical badge before verify.
        $evals = [];
        foreach ($sessions as $s) {
            $evals[$s->id] = $service->evaluate((int) $bizId, $s);
        }

        return view('clinicLab::reviews.index', compact('sessions', 'reviews', 'evals'));
    }

    public function review($sessionId, ResultReviewService $service)
    {
        $this->guardReview();
        $review = CllResultReview::forBusiness($this->bizId())
            ->where('test_session_id', $sessionId)->firstOrFail();
        $service->review($review);
        return back()->with('status', ['success' => 1, 'msg' => 'Result marked reviewed.']);
    }

    public function verify($sessionId, ResultReviewService $service)
    {
        $this->guardVerify();
        $review = CllResultReview::forBusiness($this->bizId())
            ->where('test_session_id', $sessionId)->firstOrFail();
        $service->verify($review);
        return back()->with('status', ['success' => 1, 'msg' => 'Result verified — alerts/notifications dispatched and the order updated.']);
    }
}
