<?php

namespace FluxCms\Core\Http\Middleware;

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

class CmsAccess
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next, string $permission = 'view'): Response
    {
        $user = Auth::user();

        if (! $user) {
            return redirect()->route('login');
        }

        // Check if user has CMS permission
        if (! $this->userHasCmsPermission($user, $permission)) {
            abort(403, 'Access denied. You do not have permission to access the CMS.');
        }

        return $next($request);
    }

    /**
     * Check if user has CMS permission
     */
    protected function userHasCmsPermission($user, string $permission): bool
    {
        // Check for Spatie Permission package
        if (method_exists($user, 'can')) {
            return $user->can("flux-cms.{$permission}") ||
                $user->hasRole('flux-cms') ||
                $user->hasRole('admin');
        }

        // Fallback: Check if user has admin role property
        if (isset($user->is_admin)) {
            return $user->is_admin;
        }

        // Default: Allow access for authenticated users (can be overridden in config)
        return config('flux-cms.auth.default_access', false);
    }
}
