<?php

namespace App\Http\Controllers\Portal;

use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;

class AuthController extends Controller
{
    public function login(): View|RedirectResponse
    {
        if (Auth::check() && Auth::user()->role === 'client') {
            return redirect()->route('portal.dashboard');
        }

        return view('portal.login');
    }

    public function authenticate(Request $request): RedirectResponse
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);

        $this->ensureIsNotRateLimited($request);

        if (Auth::attempt($credentials)) {
            $user = Auth::user();

            if ($user->role === 'client' && $user->active) {
                RateLimiter::clear($this->throttleKey($request));
                $request->session()->regenerate();

                if ($user->active_branch_id) {
                    return redirect()->route('portal.dashboard');
                }

                $branches = $user->branches;

                if ($branches->count() === 1) {
                    $user->update(['active_branch_id' => $branches->first()->id]);

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

                return redirect()->route('portal.branches.select');
            }

            Auth::logout();
            RateLimiter::hit($this->throttleKey($request));

            return back()->withErrors([
                'email' => 'Unauthorized access.',
            ])->onlyInput('email');
        }

        RateLimiter::hit($this->throttleKey($request));

        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.',
        ])->onlyInput('email');
    }

    public function logout(Request $request): RedirectResponse
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

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

    protected function ensureIsNotRateLimited(Request $request): void
    {
        if (! RateLimiter::tooManyAttempts($this->throttleKey($request), 5)) {
            return;
        }

        $seconds = RateLimiter::availableIn($this->throttleKey($request));

        throw ValidationException::withMessages([
            'email' => trans('auth.throttle', [
                'seconds' => $seconds,
                'minutes' => ceil($seconds / 60),
            ]),
        ]);
    }

    protected function throttleKey(Request $request): string
    {
        return Str::transliterate(Str::lower($request->input('email')).'|'.$request->ip());
    }
}
