<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\Auth\AuthAuditLogger;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\Validator;
use Illuminate\View\View;

class PasswordResetLinkController extends Controller
{
    public function __construct(
        private readonly AuthAuditLogger $authAuditLogger,
    ) {
    }

    /**
     * Display the password reset link request view.
     */
    public function create(): View
    {
        return view('auth.forgot-password');
    }

    /**
     * Handle an incoming password reset link request.
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request): RedirectResponse
    {
        $validator = Validator::make($request->all(), [
            'email' => ['required', 'email'],
        ]);

        if ($validator->fails()) {
            $this->authAuditLogger->log(
                eventType: 'forgot_password',
                request: $request,
                status: 'failed',
                reason: 'validation_failed',
                identifier: (string) $request->input('email'),
                metadata: ['fields' => array_keys($validator->errors()->toArray())],
            );

            $validator->validate();
        }

        $validated = $validator->validated();
        $email = strtolower(trim((string) $validated['email']));
        $user = User::query()->whereRaw('LOWER(email) = ?', [$email])->first();

        $status = Password::sendResetLink(
            ['email' => $email]
        );

        $success = $status === Password::RESET_LINK_SENT;

        $this->authAuditLogger->log(
            eventType: 'forgot_password',
            request: $request,
            status: $success ? 'success' : 'failed',
            reason: strtolower((string) $status),
            identifier: $email,
            user: $user,
        );

        return $success
                    ? back()->with('status', __($status))
                    : back()->withInput(['email' => $email])
                        ->withErrors(['email' => __($status)]);
    }
}
