<?php

namespace App\Http\Middleware;

use App\Services\Settings\SettingsService;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class PreventRequestsDuringPlatformMaintenance
{
    public function __construct(private readonly SettingsService $settings) {}

    /**
     * Handle an incoming request.
     *
     * @param  Closure(Request): Response  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if (! $this->isMaintenanceEnabled() || $this->shouldBypassMaintenance($request)) {
            return $next($request);
        }

        $message = (string) $this->settings->get(
            'general.maintenance_mode_message',
            'We are improving the platform and will be back shortly.'
        );

        if ($request->expectsJson()) {
            return response()->json([
                'message' => $message,
            ], Response::HTTP_SERVICE_UNAVAILABLE)->header('Retry-After', '3600');
        }

        return response()
            ->view('errors.maintenance', [
                'appName' => $this->settings->get('general.application_name', config('app.name', 'RemoteMatch AI')),
                'message' => $message,
            ], Response::HTTP_SERVICE_UNAVAILABLE)
            ->header('Retry-After', '3600');
    }

    private function isMaintenanceEnabled(): bool
    {
        return $this->settings->isEnabled('general.maintenance_mode_enabled');
    }

    private function shouldBypassMaintenance(Request $request): bool
    {
        if ($request->is('admin*', 'livewire*', 'webhooks/*', 'up')) {
            return true;
        }

        return false;
    }
}
