<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\Auth\AuthAuditLogger;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules;
use Illuminate\View\View;

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

    /**
     * Display the password reset view.
     */
    public function create(Request $request): View
    {
        return view('auth.reset-password', ['request' => $request]);
    }

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

        if ($validator->fails()) {
            $this->authAuditLogger->log(
                eventType: 'reset_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::reset(
            [
                'email' => $email,
                'password' => (string) $validated['password'],
                'password_confirmation' => (string) $request->input('password_confirmation'),
                'token' => (string) $validated['token'],
            ],
            function (User $user) use ($request) {
                $user->forceFill([
                    'password' => Hash::make($request->password),
                    'remember_token' => Str::random(60),
                ])->save();

                event(new PasswordReset($user));
            }
        );

        $success = $status === Password::PASSWORD_RESET;

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

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