<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Services\OrderRiskDetectionService;

class DetectOrderRisks extends Command
{
    protected $signature = 'orders:detect-risks {--type=all : Type of risk to detect (all, late, cancellation, rejection, payment)}';
    protected $description = 'Detect and flag order-related risks automatically';

    public function handle()
    {
        $type = $this->option('type');
        
        $this->info('Starting risk detection...');
        
        $results = match($type) {
            'late' => ['late_deliveries' => OrderRiskDetectionService::detectLateDeliveries()],
            'cancellation' => ['high_cancellation_restaurants' => OrderRiskDetectionService::detectHighCancellationRestaurants()],
            'rejection' => ['delivery_boy_rejections' => OrderRiskDetectionService::detectDeliveryBoyRejections()],
            'payment' => ['payment_mismatches' => OrderRiskDetectionService::detectPaymentMismatches()],
            default => OrderRiskDetectionService::runAllDetections()
        };

        foreach ($results as $riskType => $data) {
            if ($riskType === 'detection_timestamp') continue;
            
            $count = is_array($data) ? count($data) : 0;
            $this->line("✓ {$riskType}: {$count} issues detected");
        }

        $this->info('Risk detection completed successfully!');
        
        return 0;
    }
}