<?php

namespace App\Http\Controllers\API\Admin;

use App\Http\Controllers\Controller;
use App\Services\OrderRiskDetectionService;
use App\Models\OrderFlag;
use Illuminate\Http\Request;

class RiskManagementController extends Controller
{
    public function dashboard()
    {
        $riskSummary = OrderRiskDetectionService::getRiskSummary();
        $recentFlags = OrderFlag::where('resolved', false)
            ->with(['order:id,order_number,status', 'order.restaurant:id,name', 'order.user:id,name'])
            ->orderBy('severity', 'desc')
            ->orderBy('created_at', 'desc')
            ->limit(20)
            ->get();

        return response()->json([
            'success' => true,
            'data' => [
                'summary' => $riskSummary,
                'recent_flags' => $recentFlags,
                'alerts' => [
                    'critical_count' => $riskSummary['critical_flags'],
                    'high_count' => $riskSummary['high_flags'],
                    'requires_attention' => $riskSummary['critical_flags'] > 0 || $riskSummary['high_flags'] > 5
                ]
            ]
        ]);
    }

    public function runDetection(Request $request)
    {
        $type = $request->input('type', 'all');
        
        $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()
        };

        $totalIssues = collect($results)->except('detection_timestamp')->sum(function($data) {
            return is_array($data) ? count($data) : 0;
        });

        return response()->json([
            'success' => true,
            'message' => "Risk detection completed. {$totalIssues} issues detected.",
            'data' => $results
        ]);
    }

    public function getCriticalAlerts()
    {
        $criticalFlags = OrderFlag::where('severity', 'critical')
            ->where('resolved', false)
            ->with(['order:id,order_number,status,total', 'order.restaurant:id,name', 'order.user:id,name'])
            ->orderBy('created_at', 'desc')
            ->get();

        return response()->json([
            'success' => true,
            'data' => $criticalFlags
        ]);
    }

    public function getHighRiskRestaurants()
    {
        $highRiskFlags = OrderFlag::where('type', 'multiple_rejects')
            ->where('resolved', false)
            ->with(['order.restaurant:id,name,phone,address'])
            ->get()
            ->groupBy('order.restaurant.id')
            ->map(function($flags, $restaurantId) {
                $restaurant = $flags->first()->order->restaurant;
                return [
                    'restaurant' => $restaurant,
                    'flag_count' => $flags->count(),
                    'latest_issue' => $flags->sortByDesc('created_at')->first()->description,
                    'severity' => $flags->max('severity')
                ];
            })
            ->values();

        return response()->json([
            'success' => true,
            'data' => $highRiskFlags
        ]);
    }

    public function updateThresholds(Request $request)
    {
        $validated = $request->validate([
            'late_delivery_minutes' => 'nullable|integer|min:10|max:120',
            'restaurant_cancellation_rate' => 'nullable|numeric|min:0.05|max:0.50',
            'delivery_rejection_count' => 'nullable|integer|min:2|max:10',
            'payment_mismatch_tolerance' => 'nullable|numeric|min:0.01|max:1.00'
        ]);

        OrderRiskDetectionService::updateThresholds($validated);

        return response()->json([
            'success' => true,
            'message' => 'Risk detection thresholds updated successfully'
        ]);
    }

    public function resolveFlag(Request $request, OrderFlag $flag)
    {
        $validated = $request->validate([
            'resolution_notes' => 'nullable|string|max:500'
        ]);

        $flag->update([
            'resolved' => true,
            'description' => $flag->description . ' | RESOLVED: ' . ($validated['resolution_notes'] ?? 'No notes provided')
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Flag resolved successfully'
        ]);
    }

    public function bulkResolveFlags(Request $request)
    {
        $validated = $request->validate([
            'flag_ids' => 'required|array',
            'flag_ids.*' => 'exists:order_flags,id',
            'resolution_notes' => 'nullable|string|max:500'
        ]);

        $updated = OrderFlag::whereIn('id', $validated['flag_ids'])
            ->update([
                'resolved' => true,
                'updated_at' => now()
            ]);

        return response()->json([
            'success' => true,
            'message' => "{$updated} flags resolved successfully"
        ]);
    }
}