<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CustomerQualityPermissionMiddleware
{
    public function handle(Request $request, Closure $next): Response
    {
        $admin = auth('admin')->user();

        if (! $admin) {
            abort(403, 'Customer Quality access denied.');
        }

        $modules = (array) json_decode((string) data_get($admin, 'role.modules', '[]'), true);
        $roleName = strtolower(trim((string) data_get($admin, 'role.name', '')));
        $isSuperAdmin = (int) $admin->role_id === 1;
        $isMarketingAdmin = str_contains($roleName, 'marketing');
        $hasExplicitPermission = in_array('customer_quality_meta', $modules, true);

        if (! $isSuperAdmin && ! $isMarketingAdmin && ! $hasExplicitPermission) {
            abort(403, 'Customer Quality access is limited to Super Admin and Marketing Admin roles.');
        }

        return $next($request);
    }
}
