<?php

namespace App\Http\Controllers\Dealers;

use App\Enum\Status;
use App\Models\Role;
use App\Models\Term;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Models\Dealers\Dealer;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
use Illuminate\Validation\ValidationException;

class AuthenticatedSessionController extends Controller
{
    /**
     * Display the dealer login view.
     */
    public function create(): View
    {
        $term = Term::wherePosition('login_page')->first();
        return view('dealer.auth.login', compact('term'));
    }

    /**
     * Handle an incoming dealer authentication request.
     */
    public function store(LoginRequest $request): RedirectResponse
    {
        $request->authenticate();

        $request->session()->regenerate();

        // Check if user has dealer role
        if (!auth()->user()->hasRole(Role::DEALER)) {
            Auth::guard('web')->logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();
            throw ValidationException::withMessages([
                'email' => [trans('auth.dealer_not_authorized')],
            ]);
        }

        // Check if dealer is verified/approved
        $dealer = Dealer::withWhereHas('user', function ($q) {
            $q->where('id', auth()->id());
        })->first();

        if (!$dealer) {
            Auth::guard('web')->logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();
            throw ValidationException::withMessages([
                'email' => [trans('auth.dealer_profile_not_found')],
            ]);
        }
        dd(auth()->user()->status);
        // Check if dealer is approved (status = 1) and user is active
        if (auth()->user()->status !== Status::ACTIVE) {
            Auth::guard('web')->logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();
            throw ValidationException::withMessages([
                'email' => [trans('auth.dealer_pending_approval')],
            ]);
        }

        return redirect()->intended(route('dealers.dashboard'));
    }
}

