<?php

namespace App\Modules\Operations\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Inventory\Stock\Services\InventoryStockRebuildService;
use App\Modules\Operations\Models\OperationalControlEvent;
use App\Modules\Operations\Requests\OperationalInventoryRebuildRequest;
use App\Modules\Operations\Requests\OperationalInventoryReconcileRequest;
use App\Modules\Operations\Services\OperationalControlRebuildRunner;
use Illuminate\Http\RedirectResponse;

class OperationalControlInventoryActionController extends Controller
{
    public function __construct(
        private readonly OperationalControlRebuildRunner $runner,
        private readonly InventoryStockRebuildService $stockRebuild,
    ) {}

    public function rebuild(OperationalInventoryRebuildRequest $request): RedirectResponse
    {
        $this->authorize('viewAny', OperationalControlEvent::class);
        abort_unless($request->user()?->can('operations.control.manage'), 403);

        $tenantId = (int) $request->user()->tenant_id;
        $this->runner->rebuildAndAudit($tenantId, (int) $request->user()->id);

        return redirect()
            ->route('operations.control-center.index')
            ->with('status', __('operations_control.flash.rebuild_done'));
    }

    public function reconcileCheck(OperationalInventoryReconcileRequest $request): RedirectResponse
    {
        $this->authorize('viewAny', OperationalControlEvent::class);
        abort_unless($request->user()?->can('operations.control.manage'), 403);

        $tenantId = (int) $request->user()->tenant_id;
        $drift = $this->stockRebuild->detectMismatch($tenantId);
        $this->runner->recordDriftCheck($tenantId, $drift, (int) $request->user()->id);

        return redirect()
            ->route('operations.control-center.index')
            ->with('status', $drift
                ? __('operations_control.flash.drift_detected')
                : __('operations_control.flash.no_drift'));
    }
}
