<?php

namespace App\Http\Controllers;

use App\Facades\Settings;
use App\Jobs\ProcessPendingProviderNotifications;
use Illuminate\Http\Request;
use Mtc\MercuryDataModels\PendingProviderNotification;

class AutoGrabNotificationController extends Controller
{
    private const PROVIDER = 'autograb';

    /**
     * The only webhook event we still act on. New stock and stock updates are handled by
     * the once-daily Parquet feed (see ImportAutoGrabFeed) to keep webhook volume — which
     * was destabilising the system — to a minimum; only removals need to be near real time
     * (SFSSA-114). Every other event (adds, updates, REPROCESS, ...) is acknowledged and
     * dropped without touching the pending queue.
     */
    private const ACTIONABLE_EVENT = 'DEACTIVATE';

    public function store(Request $request)
    {
        if ($request->input('event') === self::ACTIONABLE_EVENT) {
            PendingProviderNotification::capture(
                self::PROVIDER,
                $request->input('lead.rego')
                    ?? $request->input('lead.vin')
                    ?? $request->input('lead.id'),
                $request->input(),
                $request->input('event'),
            );

            $this->dispatchDrainIfBacklogReached();
        }

        return response([
            'status' => 'received',
        ]);
    }

    /**
     * Hand the backlog to the serialized drainer once it reaches the configured size.
     * The drainer is unique per (tenant, provider), so repeat dispatches collapse into
     * one; the scheduled flush drains anything left below the threshold.
     */
    private function dispatchDrainIfBacklogReached(): void
    {
        $threshold = max(1, (int) Settings::get('stock-autograb-batch-threshold', 100));

        $pending = PendingProviderNotification::query()
            ->where('provider', self::PROVIDER)
            ->count();

        if ($pending >= $threshold) {
            ProcessPendingProviderNotifications::dispatch(self::PROVIDER);
        }
    }
}
