<?php

namespace App\Http\Middleware;

use App\Enums\EarnMemberStatus;
use App\Models\EarnMember;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

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

        if (! $member instanceof EarnMember || $member->trashed() || $member->status !== EarnMemberStatus::Active) {
            auth('earn')->logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();

            return redirect()->route('earn.login')->withErrors([
                'email' => __('earn_portal.account_unavailable'),
            ]);
        }

        return $next($request);
    }
}
