<?php

namespace App\Http\Middleware;

use App\Enums\StatusEnum;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class MaintenanceMode
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        try {
            // Skip maintenance check for auth routes, assets and maintenance page itself
            if ($request->is('login') ||
                $request->is('auth/*') ||
                $request->is('logout') ||
                $request->is('maintenance') ||
                $request->is('build/*') ||
                $request->is('assets/*') ||
                $request->is('storage/*')) {
                return $next($request);
            }

            // Check if maintenance mode is enabled
            if (site_settings('maintenance_mode') == (StatusEnum::true)->status()) {
                // Check if user is authenticated
                if (Auth::check()) {
                    // Allow access if user is owner (owner = 1)
                    if (Auth::user()->owner == StatusEnum::true->status()) {
                        return $next($request);
                    }

                    // Redirect non-owner users to maintenance page
                    if ($request->expectsJson()) {
                        return response()->json(['message' => 'Site is under maintenance'], 503);
                    }

                    return redirect()->route('maintenance');
                }

                // Redirect unauthenticated users to login
                return redirect()->route('auth.login');
            }

            return $next($request);

        } catch (\Exception $e) {
            // If there's an error, allow request to proceed
            return $next($request);
        }
    }
}
