<?php

use MintyPHP\Http\ApiAuth;
use MintyPHP\Http\ApiBootstrap;
use MintyPHP\Http\ApiResponse;
use MintyPHP\Service\User\UserServicesFactory;

ApiBootstrap::init();
ApiResponse::requireMethod('POST');

$request = requestInput();

ApiResponse::requireAbility(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_API_ME_SELF_UPDATE);

$input = $request->bodyAll();
$currentPassword = (string) ($input['current_password'] ?? '');
$password = (string) ($input['password'] ?? '');
$password2 = (string) ($input['password2'] ?? '');

$validationErrors = formErrors();
if ($currentPassword === '') {
    $validationErrors->add('current_password', 'required');
}
if ($password === '') {
    $validationErrors->add('password', 'required');
}
if ($password2 === '') {
    $validationErrors->add('password2', 'required');
}
if ($validationErrors->hasAny()) {
    ApiResponse::validationFromFormErrors($validationErrors);
}

$userServicesFactory = app(UserServicesFactory::class);
$userAccountService = $userServicesFactory->createUserAccountService();
$userPasswordService = $userServicesFactory->createUserPasswordService();

$userId = ApiAuth::userId();
$user = $userAccountService->findById($userId);
if (!$user) {
    ApiResponse::error('user_not_found', 404);
}

if (!password_verify($currentPassword, (string) ($user['password'] ?? ''))) {
    ApiResponse::validationFromFormErrors(formErrorsFrom(['current_password' => ['invalid']]));
}

$result = $userPasswordService->resetPassword($userId, $password, $password2);
if (!($result['ok'] ?? false)) {
    $errors = $result['errors'] ?? [];
    if ($errors) {
        ApiResponse::validationFromFormErrors(formErrors()->addMany('password', $errors));
    }
    ApiResponse::error('password_change_failed', 422);
}

ApiResponse::noContent();
