<?php

namespace Controllers;

use Libs\ResponseLib;
use Models\UserModel;
use Psr\Http\Message\ServerRequestInterface;
use Respect\Validation\Validator as val;
use Respect\Validation\Exceptions\ValidationException;

class UserChangePasswordController
{
    private UserModel $model;

    public function __construct()
    {
        $this->model = new UserModel();
    }

    public function __invoke(ServerRequestInterface $request)
    {
        $userId = (int)($request->getAttribute('api_user_id') ?? 0);
        if ($userId <= 0) {
            return ResponseLib::sendFail('Unauthorized', [], 'E_VALIDATE')->withStatus(401);
        }

        $body = json_decode((string)$request->getBody(), true) ?? [];

        try {
            val::key('current_password', val::stringType()->notEmpty())
                ->key('new_password', val::stringType()->notEmpty()->length(8, null))
                ->assert($body);
        } catch (ValidationException $e) {
            return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
        }

        $current = $body['current_password'];
        $new = $body['new_password'];

        if ($current === $new) {
            return ResponseLib::sendFail('New password must be different from current password', [], 'E_VALIDATE')->withStatus(400);
        }

        $ok = $this->model->changePassword($userId, $current, $new);
        if (!$ok) {
            return ResponseLib::sendFail('Invalid current password or update failed', [], 'E_VALIDATE')->withStatus(400);
        }

        return ResponseLib::sendOk(['user_id' => $userId], 'S_UPDATED');
    }
}