<?php

namespace App\Services;

use App\Models\Vendor;

/**
 * Maintains each vendor's order-responsiveness metrics: how often they accept
 * (vs decline / let the clock run out) and how quickly. Feeds a 0–100
 * response_score used for badges, ranking and tier decisions — soft signals,
 * never an automatic ban.
 */
class VendorResponseService
{
    /** Minimum decisions before a score is meaningful. */
    private const MIN_SAMPLE = 5;

    /** response_score at/above this earns the "Fast responder" badge. */
    public const FAST_THRESHOLD = 80;

    public function recordAccepted(Vendor $vendor, int $responseSeconds): void
    {
        $vendor->increment('resp_accepted');
        $vendor->increment('resp_total_seconds', max(0, $responseSeconds));
        $this->recompute($vendor->fresh());
    }

    public function recordRejected(Vendor $vendor): void
    {
        $vendor->increment('resp_rejected');
        $this->recompute($vendor->fresh());
    }

    public function recordTimedOut(Vendor $vendor): void
    {
        $vendor->increment('resp_timed_out');
        $this->recompute($vendor->fresh());
    }

    /** Recalculate the cached average response time + 0–100 score. */
    public function recompute(Vendor $vendor): void
    {
        $accepted  = (int) $vendor->resp_accepted;
        $rejected  = (int) $vendor->resp_rejected;
        $timedOut  = (int) $vendor->resp_timed_out;
        $decisions = $accepted + $rejected + $timedOut;

        $avg = $accepted > 0 ? (int) round($vendor->resp_total_seconds / $accepted) : null;

        $score = null;
        if ($decisions >= self::MIN_SAMPLE) {
            $acceptanceRate = $accepted / $decisions; // 0..1

            // 70% weight on accepting reliably, 30% on speed.
            $speed = match (true) {
                $avg === null   => 0.0,
                $avg <= 5 * 60  => 1.0,
                $avg <= 15 * 60 => 0.66,
                $avg <= 30 * 60 => 0.33,
                default         => 0.0,
            };

            $score = (int) round($acceptanceRate * 70 + $speed * 30);
        }

        $vendor->forceFill([
            'avg_response_seconds' => $avg,
            'response_score'       => $score,
        ])->save();
    }
}
