<?php

namespace App\Http\Controllers\Admin\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Auth\Events\Validated;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;

/**
 * PRC-252 — admin "confirm password" challenge in front of sensitive
 * endpoints (password change, role assignment, …). Implements the
 * standard Laravel `password.confirm` named-route contract so the
 * built-in middleware can redirect to /admin/confirm-password when
 * the session's `auth.password_confirmed_at` is missing or older than
 * `config('auth.password_timeout')` (default 3 hours).
 */
final class ConfirmablePasswordController extends Controller
{
    /**
     * Display the password confirmation form.
     */
    public function show(): View
    {
        return view('admin.auth.confirm-password');
    }

    /**
     * Validate the admin's password and mark the session as confirmed.
     */
    public function store(Request $request): RedirectResponse
    {
        $admin = Auth::guard('admin')->user();

        if (! $admin || ! Auth::guard('admin')->validate([
            'email' => $admin->email,
            'password' => (string) $request->input('password'),
        ])) {
            throw ValidationException::withMessages([
                'password' => __('auth.password'),
            ]);
        }

        event(new Validated('admin', $admin));

        $request->session()->put('auth.password_confirmed_at', time());

        return redirect()->intended(route('admin.dashboard'));
    }
}
