<?php

namespace App\Http\Middleware;

use App\Services\MobileConfig\MobileConfigService;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class MobileMaintenanceMiddleware
{
    public function __construct(
        protected MobileConfigService $service
    ) {}

    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Only apply to mobile API v1 routes
        if (! $request->is('api/v1/*')) {
            return $next($request);
        }

        $config = $this->service->all();
        $control = $config['control_center'] ?? [];
        $updates = $config['app_updates'] ?? [];

        // 1. Check KILL SWITCH (Emergency Maintenance)
        if (filter_var($control['kill_switch_active'] ?? false, FILTER_VALIDATE_BOOLEAN)) {
            // Check IP Bypass
            $bypassIps = array_map('trim', explode(',', $control['maintenance_bypass_ips'] ?? ''));
            if (! in_array($request->ip(), $bypassIps)) {
                return response()->json([
                    'status' => 'maintenance',
                    'message' => $control['kill_switch_message'] ?? 'System is currently undergoing emergency maintenance.',
                    'maintenance_info' => [
                        'start' => $control['maintenance_start_at'] ?? null,
                        'end' => $control['maintenance_end_at'] ?? null,
                    ],
                ], 503);
            }
        }

        // 2. Check APP VERSION (Force Update)
        $clientVersion = $request->query('v') ?: $request->header('X-App-Version');
        $minVersion = $updates['min_app_version'] ?? '1.0.0';

        if ($clientVersion && version_compare($clientVersion, $minVersion, '<')) {
            return response()->json([
                'status' => 'upgrade_required',
                'message' => 'A mandatory update is required to continue using the application.',
                'current_version' => $clientVersion,
                'required_version' => $minVersion,
                'update_urls' => [
                    'android' => $updates['store_url_android'] ?? null,
                    'ios' => $updates['store_url_ios'] ?? null,
                ],
            ], 426); // 426 Upgrade Required
        }

        return $next($request);
    }
}
