<?php

namespace App\Http\Controllers\Auth;

use App\Enum\Status;
use App\Models\Role;
use App\Models\Term;
use App\Models\User;
use Illuminate\View\View;
use Illuminate\Http\Request;
use App\Services\GetIPInfoService;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\RedirectResponse;
use App\Http\Requests\Auth\LoginRequest;
use App\Services\ActivityLogs\AuthLogService;
use App\Services\ActivityLogs\TermsAndConditionsLogService;

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

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

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

        $user = auth()->user();
        // Block suspended dealers
        if ($user->hasRole(Role::DEALER) && $user->status === Status::SUSPENDED) {
            Auth::logout();
            return redirect()->back()->withErrors([
                'email' => 'Your dealer account is suspended.',
            ]);
        }

        // Block suspended buyers
        if ($user->hasRole(Role::BUYER) && $user->status === Status::SUSPENDED) {
            Auth::logout();
            return redirect()->back()->withErrors([
                'email' => 'Your buyer account is suspended.',
            ]);
        }

        (new TermsAndConditionsLogService())->accepted('login');
        (new AuthLogService())->loggedIn();

        if(auth()->user()->hasRole(Role::DEALER)){
            return redirect()->route('dealers.dashboard');
        }

        if(auth()->user()->hasRole(Role::BUYER)){
            return redirect()->route('buyers.dashboard');
        }

        return redirect()->route(
            'dashboard'
        );
    }

    /**
     * Destroy an authenticated session.
     */
    public function destroy(Request $request): RedirectResponse
    {
        (new AuthLogService())->loggedOut();

        Auth::guard('web')->logout();

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

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

        return redirect('/');
    }
}
