<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class AdminMiddleware
{
    /**
     * Usage:
     *   ->middleware(['admin'])              → admin ONLY (moderators denied)
     *   ->middleware(['admin:animes.edit'])  → admin, OR moderator WITH that permission
     */
    public function handle(Request $request, Closure $next, string $permission = null)
    {
        if (!auth()->check()) {
            return redirect()->route('admin.login');
        }

        $user = auth()->user();

        // Admins always pass
        if ($user->isAdmin()) {
            return $next($request);
        }

        // Must be at least a moderator
        if ($user->role !== 'moderator') {
            abort(403, 'Bu alana erişim yetkiniz yok.');
        }

        // Moderators always need a specific permission — no blanket access
        if (!$permission || !$user->can_mod($permission)) {
            if ($request->expectsJson()) {
                return response()->json(['error' => 'Bu işlem için yetkiniz yok.'], 403);
            }
            return back()->with('error', 'Bu sayfaya erişim için gerekli izne sahip değilsiniz.');
        }

        return $next($request);
    }
}
