<?php

namespace App\Http\Controllers\Care;

use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Http\Controllers\Controller;
use App\Models\InvestigationRequest;
use App\Models\InvestigationType;
use App\Services\Care\BranchContext;
use App\Services\Care\CarePermissions;
use App\Services\Care\InvestigationService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

class LabAdminController extends Controller
{
    use ScopesToAccount;

    public function __construct(
        protected InvestigationService $investigations,
        protected BranchContext $branchContext,
    ) {}

    public function index(Request $request): View
    {
        $this->authorizeAbility($request, 'lab.catalog.manage');
        $organization = $this->organization($request);
        $member = $this->member($request);
        $owner = $this->ownerRef($request);
        $branches = $this->branchContext->branches($request, $organization, $member);
        $branchId = $this->branchContext->resolve($request, $organization, $member);
        $branchScope = $branchId > 0 ? $branchId : null;

        $catalogCount = InvestigationType::query()
            ->where('organization_id', $organization->id)
            ->count();

        $activeCatalogCount = InvestigationType::query()
            ->where('organization_id', $organization->id)
            ->where('is_active', true)
            ->count();

        $queueCounts = InvestigationRequest::owned($owner)
            ->where('organization_id', $organization->id)
            ->when($branchScope, fn ($q) => $q->where('branch_id', $branchScope))
            ->whereIn('status', [
                InvestigationRequest::STATUS_PENDING,
                InvestigationRequest::STATUS_SAMPLE_COLLECTED,
                InvestigationRequest::STATUS_IN_PROGRESS,
                InvestigationRequest::STATUS_AWAITING_REVIEW,
            ])
            ->select('status', DB::raw('count(*) as total'))
            ->groupBy('status')
            ->pluck('total', 'status');

        $openQueue = (int) $queueCounts->sum();
        $queue = $branchScope
            ? $this->investigations->workQueue($owner, $branchScope)
            : collect();

        return view('care.lab.admin.index', [
            'organization' => $organization,
            'branches' => $branches,
            'branchId' => $branchId,
            'canSwitchBranch' => $this->branchContext->canSwitch($member),
            'catalogCount' => $catalogCount,
            'activeCatalogCount' => $activeCatalogCount,
            'openQueue' => $openQueue,
            'queueCounts' => $queueCounts,
            'recentQueue' => $queue->take(8),
            'statuses' => config('care.investigation_statuses'),
            'isAdmin' => app(CarePermissions::class)->isAdmin($member),
        ]);
    }
}
