<?php

namespace App\Console\Commands;

use App\Models\Central\Company;
use App\Models\Tenant\Supplier;
use App\Services\Warehouse\SupplierAnalytics;
use App\Tenancy\TenantManager;
use Illuminate\Console\Command;

class RateSuppliersCommand extends Command
{
    protected $signature = 'suppliers:rate
                            {--days=90 : Look-back window in days}
                            {--slug= : Only one tenant by slug}';

    protected $description = 'Recompute auto-rating for every supplier based on on-time deliveries, speed and volume.';

    public function handle(SupplierAnalytics $analytics): int
    {
        $query = Company::query()->where('status', '!=', 'archived');
        if ($slug = $this->option('slug')) {
            $query->where('slug', $slug);
        }
        $companies = $query->get();
        $days = (int) $this->option('days');

        $totalUpdated = 0;

        foreach ($companies as $company) {
            app(TenantManager::class)->setCurrent($company);

            $suppliers = Supplier::where('is_active', true)->get();
            $changed = 0;
            foreach ($suppliers as $supplier) {
                $score = $analytics->computedRating($supplier, $days);
                if ($score !== null && $score !== (int) $supplier->rating) {
                    $supplier->rating = $score;
                    $supplier->saveQuietly();
                    $changed++;
                }
            }

            $this->info(sprintf('[%s] suppliers rated, %d updated', $company->slug, $changed));
            $totalUpdated += $changed;
        }

        $this->info("Total suppliers updated: {$totalUpdated}");
        return self::SUCCESS;
    }
}
