<?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';

    /**
     * Event types that carry no actionable change and are dropped on receipt.
     */
    private const IGNORED_EVENTS = ['REPROCESS'];

    public function store(Request $request)
    {
        // Skip leads we never import: private sellers (see AutoGrabToVehicleImport::add)
        // and ignorable event types such as REPROCESS, which carry no new state.
        $isPrivate = $request->input('lead.seller_type') === 'private';
        $isIgnoredEvent = in_array($request->input('event'), self::IGNORED_EVENTS, true);

        if (!$isPrivate && !$isIgnoredEvent) {
            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);
        }
    }
}
