<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Models\Association;

class EnsureAssociationAdmin
{
    /**
     * Ensure the authenticated user has an admin role in their active association.
     *
     * Optionally accepts a permission parameter to check granular permissions:
     *   middleware('association.admin:manage_payments')
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     * @param  string|null  $permission  Optional permission slug to check (e.g., 'manage_payments')
     */
    public function handle(Request $request, Closure $next, ?string $permission = null): Response
    {
        $user = $request->user();

        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthenticated.',
            ], 401);
        }

        // Resolve the user's active association
        $associationId = $user->last_association_context
            ?? $user->associations->first()?->id;

        if (!$associationId) {
            return response()->json([
                'success' => false,
                'message' => 'No association context found.',
            ], 403);
        }

        $association = Association::find($associationId);

        if (!$association) {
            return response()->json([
                'success' => false,
                'message' => 'Association not found.',
            ], 404);
        }

        // Check if the user has admin-level access in this association
        if (!$user->hasAdminRoleInAssociation($association)) {
            return response()->json([
                'success' => false,
                'message' => 'You do not have administrative access to perform this action.',
            ], 403);
        }

        // If a specific permission is required, verify it
        if ($permission) {
            $role = $user->getRoleInAssociation($association);

            if (!$role) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unable to resolve your role in this association.',
                ], 403);
            }

            $permissions = $role->permissions ?? [];

            // Wildcard ('*') grants all permissions
            if (!in_array('*', $permissions) && !in_array($permission, $permissions)) {
                return response()->json([
                    'success' => false,
                    'message' => "You do not have the required permission: {$permission}.",
                ], 403);
            }
        }

        return $next($request);
    }
}
