<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Services\Auth\PasswordPolicyService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class PasswordController extends Controller
{
    /**
     * Update the user's password.
     */
    public function update(Request $request)
    {
        $validated = $request->validateWithBag('updatePassword', [
            'current_password' => ['required', 'current_password'],
            'password' => ['required', PasswordPolicyService::getRules(), 'confirmed'],
        ]);

        $user = $request->user();
        $newPassword = $validated['password'];

        // Check History
        PasswordPolicyService::checkHistory($user, $newPassword);

        // Must be called before password is updated so current hash still matches
        Auth::logoutOtherDevices($request->current_password);

        $passwordHash = Hash::make($newPassword);
        $user->update([
            'password' => $passwordHash,
        ]);

        // Record Change & History
        PasswordPolicyService::recordPasswordChange($user, $passwordHash);

        if ($request->expectsJson()) {
            return response()->json([
                'success' => true,
                'message' => __('Password updated successfully.'),
            ]);
        }

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