<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Models\Dealer;
use App\Models\PasswordChangeToken;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Illuminate\View\View;

class AuthenticatedSessionController extends Controller
{
    /**
     * Display the login view.
     */
    public function create(): View
    {
        return view('auth.login');
    }

    /**
     * Handle an incoming authentication request.
     */
    public function store(LoginRequest $request): RedirectResponse
    {
        $email = strtolower($request->string('email')->toString());
        $userByEmail = User::whereRaw('lower(email) = ?', [$email])->first();

        if ($userByEmail && $userByEmail->is_disabled) {
            return back()->withErrors(['email' => 'This account is disabled. Please contact an administrator.']);
        }

        $request->authenticate();

        $user = Auth::user();

        if ($user->force_password_change) {
            $token = Str::random(64);
            PasswordChangeToken::create([
                'user_id' => $user->id,
                'token_hash' => hash('sha256', $token),
                'expires_at' => now()->addMinutes(30),
            ]);

            Auth::guard('web')->logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();

            return redirect()->route('first-login.password.show', ['token' => $token])
                ->with('status', 'Set a new password to continue.');
        }

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

        return redirect()->intended(RouteServiceProvider::HOME);
    }

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

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

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

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

        if ($user && $user->dealer_id) {
            $dealerCode = Dealer::query()
                ->where('id', $user->dealer_id)
                ->value('code');

            if (is_string($dealerCode) && $dealerCode !== '') {
                return redirect()->route('dealer.login.show', ['code' => $dealerCode]);
            }
        }

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