<?php

namespace App\Providers;

use App\Models\User;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
use Laravel\Fortify\Fortify;

class FortifyServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(
            \Laravel\Fortify\Contracts\LoginResponse::class,
            \App\Http\Responses\LoginResponse::class
        );

        // Custom RegisterResponse — runs InviteController::processPendingInvite()
        // for brand-new users who registered via a /invite/{token} link, so they
        // join the inviting workspace instead of being routed into the
        // new-workspace onboarding flow.
        $this->app->singleton(
            \Laravel\Fortify\Contracts\RegisterResponse::class,
            \App\Http\Responses\RegisterResponse::class
        );
    }

    public function boot(): void
    {
        // Rate limiting — login (60 per minute — generous to avoid 429 during testing/demo)
        RateLimiter::for('login', function (Request $request) {
            $throttleKey = Str::transliterate(Str::lower($request->input(Fortify::username())) . '|' . $request->ip());
            return Limit::perMinute(60)->by($throttleKey);
        });

        // Rate limiting — two-factor challenge
        RateLimiter::for('two-factor', function (Request $request) {
            return Limit::perMinute(20)->by($request->session()->get('login.id'));
        });

        // Rate limiting — password reset
        RateLimiter::for('password-reset', function (Request $request) {
            return Limit::perHour(15)->by($request->input('email') . '|' . $request->ip());
        });

        // Rate limiting — registration
        RateLimiter::for('registration', function (Request $request) {
            return Limit::perMinute(10)->by($request->ip());
        });

        // Custom auth logic
        Fortify::authenticateUsing(function (Request $request) {
            // reCAPTCHA gate — runs FIRST so a missing/bad token never
            // even enters the user-lookup path. Admin-controlled via
            // Admin → Security → Login Security → CAPTCHA Protection.
            // No-op when captcha_enabled is false OR the keys are blank
            // (half-configured captcha silently disables; see
            // App\Support\Captcha::isEnabled()).
            if (\App\Support\Captcha::isEnabled()) {
                $token = (string) (
                    $request->input('g-recaptcha-response')
                    ?? $request->input('captcha_response')
                    ?? ''
                );
                if (!\App\Support\Captcha::verify($token, $request->ip())) {
                    // Throwing a ValidationException lets Fortify surface
                    // the error on the login form (under the captcha
                    // field) using the standard 422 / old() flow.
                    throw \Illuminate\Validation\ValidationException::withMessages([
                        Fortify::username() => [__('Please complete the CAPTCHA challenge to continue.')],
                    ]);
                }
            }

            // FIX-011: Case-insensitive email lookup
            // FIX-012: Check status BEFORE password to avoid timing leaks
            $user = User::whereRaw('LOWER(email) = ?', [strtolower($request->email)])->first();

            if (!$user) {
                return null;
            }

            // FIX-012: Reject suspended/banned users before password check
            if ($user->status !== 'active') {
                return null;
            }

            if (Hash::check($request->password, $user->password)) {
                return $user;
            }

            return null;
        });

        // Views
        Fortify::loginView(fn () => view('auth.login'));
        // Honor Admin → Settings → Auth → "Allow user registration" toggle.
        // When disabled, redirect both GET (form view) and bounce direct
        // POSTs from CreateNewUser action.
        Fortify::registerView(function () {
            if (\App\Models\SystemSetting::get('registration_enabled', 'true') !== 'true') {
                return redirect('/login')->with('error', __('Registration is currently disabled.'));
            }
            return view('auth.register');
        });
        Fortify::requestPasswordResetLinkView(fn () => view('auth.forgot-password'));
        Fortify::resetPasswordView(fn (Request $request) => view('auth.reset-password', ['request' => $request]));
        Fortify::verifyEmailView(fn () => view('auth.verify-email'));
        Fortify::confirmPasswordView(fn () => view('auth.confirm-password'));
        Fortify::twoFactorChallengeView(fn () => view('auth.two-factor-challenge'));

        // Custom registration
        Fortify::createUsersUsing(\App\Actions\Fortify\CreateNewUser::class);
        Fortify::updateUserProfileInformationUsing(\App\Actions\Fortify\UpdateUserProfileInformation::class);
        Fortify::updateUserPasswordsUsing(\App\Actions\Fortify\UpdateUserPassword::class);
        Fortify::resetUserPasswordsUsing(\App\Actions\Fortify\ResetUserPassword::class);
    }
}
