<?php

namespace App\Http\Middleware;

use App\Models\Sponsor;
use Closure;
use Illuminate\Http\Request;

class SponsorApiMiddleware
{
    /**
     * Authenticate incoming sponsor API requests via Bearer token.
     */
    public function handle(Request $request, Closure $next)
    {
        $authHeader = $request->header('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return response()->json([
                'success' => false,
                'message' => 'Authentication token required.'
            ], 401);
        }

        $token = substr($authHeader, 7);
        $sponsor = Sponsor::where('api_token', $token)->first();

        if (!$sponsor) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid or expired authentication token.'
            ], 401);
        }

        if ($sponsor->status === 'suspended') {
            return response()->json([
                'success' => false,
                'message' => 'Your account has been suspended. Please contact support.'
            ], 403);
        }

        // Attach sponsor to request for use in controllers
        $request->attributes->set('sponsor', $sponsor);

        return $next($request);
    }
}
