<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Models\User;
use App\Services\WalletService;

class WalletAuth
{
    public function handle(Request $request, Closure $next): Response
    {
        $walletAddress = $request->header('X-Wallet-Address') ?? $request->input('wallet_address');
        
        if (!$walletAddress) {
            return response()->json([
                'success' => false,
                'message' => 'Wallet address required'
            ], 401);
        }

        $user = User::where('wallet_address', strtolower($walletAddress))
            ->where('is_active', true)
            ->first();

        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'Wallet not connected or user inactive'
            ], 401);
        }

        // Attach user to request
        $request->merge(['user' => $user]);
        $request->setUserResolver(function () use ($user) {
            return $user;
        });

        return $next($request);
    }
}
