<?php

namespace Mtc\Modules\B2B\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Mtc\Modules\B2B\Enums\TradeCustomerStatus;
use Mtc\Modules\B2B\Models\TradeCustomer;
use Mtc\Modules\Members\Classes\Auth;

class RequireTradeCustomer
{
    public function handle(Request $request, Closure $next): mixed
    {
        if (!config('b2b.pay_on_account_enabled')) {
            abort(404);
        }

        $member = Auth::getLoggedInMember();
        if (!$member || empty($member->id)) {
            return redirect('/members/dashboard');
        }

        $tradeCustomer = TradeCustomer::where('member_id', $member->id)
            ->where('status', TradeCustomerStatus::Approved->value)
            ->with('tier')
            ->first();

        if (!$tradeCustomer) {
            return redirect('/members/dashboard')->with('error', 'You do not have an active trade account.');
        }

        // Make the trade customer available to downstream controllers via the request
        $request->attributes->set('trade_customer', $tradeCustomer);

        return $next($request);
    }
}
