<?php

namespace App\Providers;

use App\Models\LoginHistory;
use App\Models\User;
use App\Support\Tenancy;
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 boot(): void
    {
        // Login is tenant-scoped: the same email may exist at two clinics.
        // On the central domain only platform staff (tenant_id NULL) can log in.
        Fortify::authenticateUsing(function (Request $request) {
            $tenancy = app(Tenancy::class);

            $user = User::withoutGlobalScope('tenant')
                ->where('email', strtolower($request->email))
                ->when(
                    $tenancy->check(),
                    fn ($q) => $q->where('tenant_id', $tenancy->id()),
                    fn ($q) => $q->whereNull('tenant_id'),
                )
                ->where('status', 'active')
                ->first();

            $ok = $user && Hash::check($request->password, $user->password);

            if ($user) {
                LoginHistory::create([
                    'user_id' => $user->id,
                    'ip' => $request->ip(),
                    'user_agent' => Str::limit((string) $request->userAgent(), 250),
                    'successful' => $ok,
                ]);
            }

            if ($ok) {
                $user->forceFill(['last_login_at' => now()])->saveQuietly();

                return $user;
            }

            return null;
        });

        Fortify::loginView(fn () => view('auth.login'));
        Fortify::twoFactorChallengeView(fn () => view('auth.two-factor-challenge'));
        Fortify::requestPasswordResetLinkView(fn () => view('auth.forgot-password'));
        Fortify::resetPasswordView(fn (Request $r) => view('auth.reset-password', ['request' => $r]));

        RateLimiter::for('login', function (Request $request) {
            $key = strtolower((string) $request->input('email')).'|'.$request->ip();

            return Limit::perMinute(5)->by($key);
        });

        RateLimiter::for('two-factor', function (Request $request) {
            return Limit::perMinute(5)->by($request->session()->get('login.id'));
        });
    }
}
