<?php

namespace App\Modules\BaseAuth\Controllers;

use App\Models\User;
use App\Modules\BaseLocale\Middleware\SetLocale;
use Illuminate\Contracts\View\View;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class LoginController extends Controller
{
    use AuthenticatesUsers, ValidatesRequests;

    /**
     * Middleware
     */
    public function __construct()
    {
        $middleware = [];

        if (module('BaseLocale')->isEnabled()) {
            array_push($middleware, SetLocale::class);
        }

        $this->middleware($middleware)->except('logout');
    }

    /**
     * Get the login username to be used by the controller, also send via request.
     */
    public function username(): string
    {
        return config()->string('module.base-auth.default_username');
    }

    /**
     * Supports multiple usernames
     */
    public function supportsMultipleUsernames(): bool
    {
        return config()->boolean('module.base-auth.multiple_usernames');
    }

    /**
     * Supports multiple usernames
     *
     * @return array<int, string>
     */
    public function usernames(): array
    {
        /** @var array<int, string> */
        $usernames = config()->array('module.base-auth.usernames');

        return $usernames;
    }

    /**
     * Show the application's login form.
     */
    public function showLoginForm(): View
    {
        return view('module.base-auth::pages.login');
    }

    /**
     * The user has been authenticated.
     */
    protected function authenticated(Request $request, User $user): JsonResponse|RedirectResponse
    {
        $redirect = redirect()->intended($this->redirectPath());

        return $request->wantsJson()
            ? new JsonResponse([
                'redirect' => $redirect->getTargetUrl(),
            ], 200)
            : $redirect;
    }

    /**
     * Log the user out of the application.
     */
    public function logout(Request $request): RedirectResponse
    {
        $this->guard()->logout();

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

        return redirect()->intended($this->redirectPath());
    }

    /**
     * Get the post register / login redirect path.
     */
    public function redirectPath(): string
    {
        return config()->string('module.base-auth.redirect_path');
    }

    /**
     * Validate the user login request.
     *
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function validateLogin(Request $request): void
    {
        $request->validate([
            $this->username() => ['required', 'string', 'max:250'],
            'password' => ['required', 'string', 'max:250'],
        ]);
    }

    /**
     * Handle a login request to the application.
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function login(Request $request)
    {
        $this->validateLogin($request);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if (method_exists($this, 'hasTooManyLoginAttempts') && $this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        $user = User::query()
            ->when($this->supportsMultipleUsernames(), function ($query) use ($request) {
                foreach ($this->usernames() as $username) {
                    $query->orWhere($username, $request->username);
                }
            }, function ($query) use ($request) {
                $query->where($this->username(), $request->username);
            })
            ->first();

        if (! $user) {
            return $this->sendFailedLoginResponse($request);
        }

        if (Hash::check($request->string('password'), $user->password)) {
            Auth::login($user);

            if ($request->hasSession()) {
                $request->session()->put('auth.password_confirmed_at', time());
            }

            return $this->sendLoginResponse($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

    /**
     * Send the response after the user was authenticated.
     */
    protected function sendLoginResponse(Request $request): RedirectResponse|JsonResponse
    {
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user()); // @phpstan-ignore-line
    }
}
