<?php

namespace App\Domains\Auth\Controllers;

use App\Domains\Auth\Models\ResetPasswordAttempt;
use App\Domains\Auth\Requests\ResetPasswordRequest;
use App\Domains\Auth\Services\ResetPasswordAttemptService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\ValidationException;

class ResetPasswordController extends Controller
{
    public function __construct(
        private readonly ResetPasswordAttemptService $resetPasswordAttemptService,
    ) {}

    /**
     * @throws ValidationException
     */
    public function __invoke(ResetPasswordRequest $request): JsonResponse
    {
        $data = $request->validated();

        if (! $this->resetPasswordAttemptService->resetPassword(
            $data['email'],
            $data['codigo'],
            $data['password'],
        )) {
            throw ValidationException::withMessages([
                'codigo' => __('api.auth.password_reset_invalid'),
            ]);
        }

        return response()->json([
            'code' => 'auth.password_updated',
            'message' => __('api.auth.password_updated'),
            'status' => ResetPasswordAttempt::STATUS_USED,
        ]);
    }
}
