<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Support\PasswordPolicy;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class PasswordController extends Controller
{
    /**
     * Update the user's password.
     */
    public function update(Request $request): RedirectResponse
    {
        $validated = $request->validateWithBag('updatePassword', [
            'current_password' => ['required', 'current_password'],
            'password' => array_merge(PasswordPolicy::rules(), ['confirmed']),
        ], array_merge(PasswordPolicy::messages(), [
            'current_password.required' => 'Current password is required.',
            'current_password.current_password' => 'The current password is incorrect.',
        ]));

        $user = $request->user();
        if ($user->isSamePassword($request->password)) {
            return redirect()->back()->withErrors(
                ['password' => 'Your new password must be different from your current password.'],
                'updatePassword'
            );
        }

        $user->password = Hash::make($validated['password']);
        $user->force_password_change = false;
        $user->save();

        return back()->with('status', 'password-updated');
    }
}
