<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use Closure;
use App\Http\Controllers\Helpers\ResponseHelper;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Hypervel\Support\Facades\Redis;
use Hypervel\Support\Facades\Auth;
use App\Enums\UserTypes;

class CheckMaintenanceMode
{
    /**
     * Handle an incoming request.
     */
    public function handle(ServerRequestInterface $request, Closure $next): ResponseInterface
    {
        $isMaintenance = Redis::get('system:maintenance_mode') === 'true';

        if ($isMaintenance) {
            $user = Auth::user();
            
            // Allow Ultimate users to bypass maintenance mode
            if (!$user || $user->acct_type !== UserTypes::ULTIMATE) {
                // Return 503 Service Unavailable
                return ResponseHelper::returnError('System is currently under maintenance. Transactions are temporarily disabled. Please try again later.', 503);
            }
        }

        return $next($request);
    }
}
