<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\ForgotPasswordRequest;
use App\Http\Requests\ResetPasswordRequest;
use App\Services\PasswordResetService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class PasswordResetController extends Controller
{
    protected PasswordResetService $passwordResetService;

    public function __construct(PasswordResetService $passwordResetService)
    {
        $this->passwordResetService = $passwordResetService;
    }

    /**
     * Display the form to request a password reset link.
     */
    public function showLinkRequestForm(): View
    {
        return view('auth.passwords.email');
    }

    /**
     * Send a reset link to the given user.
     */
    public function sendResetLinkEmail(ForgotPasswordRequest $request): RedirectResponse
    {
        // Check rate limiting
        if ($this->passwordResetService->isRateLimited($request->email, $request->ip())) {
            $remaining = $this->passwordResetService->remainingAttempts($request->email);
            return back()->withErrors([
                'email' => __("Too many reset attempts. Please try again later. Remaining attempts: :remaining", ['remaining' => $remaining]),
            ]);
        }

        $result = $this->passwordResetService->sendResetLink(
            $request->email,
            $request->ip(),
            $request->userAgent()
        );

        return back()->with('status', $result['message']);
    }

    /**
     * Display the password reset view.
     */
    public function showResetForm(Request $request, string $token): View
    {
        $email = $request->email;

        // Validate token
        $valid = $this->passwordResetService->validateToken($token, $email);

        if (!$valid) {
            return view('auth.passwords.expired');
        }

        return view('auth.passwords.reset', compact('token', 'email'));
    }

    /**
     * Reset the given user's password.
     */
    public function reset(ResetPasswordRequest $request): RedirectResponse
    {
        $result = $this->passwordResetService->reset(
            $request->email,
            $request->token,
            $request->password,
            $request->ip()
        );

        if (!$result['success']) {
            return back()->withErrors(['email' => $result['message']]);
        }

        return redirect()->route('login')
            ->with('status', $result['message']);
    }

    /**
     * Check reset rate limit via AJAX.
     */
    public function checkRateLimit(Request $request): JsonResponse
    {
        $request->validate([
            'email' => ['required', 'string', 'email'],
        ]);

        $isLimited = $this->passwordResetService->isRateLimited($request->email, $request->ip());
        $remaining = $this->passwordResetService->remainingAttempts($request->email);

        return response()->json([
            'limited' => $isLimited,
            'remaining' => $remaining,
        ]);
    }
}
