<?php

namespace Controllers;

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

class UserCheckStatus
{
    public function __invoke(ServerRequestInterface $request)
    {
        $body = json_decode((string)$request->getBody(), true) ?? [];

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

        $numberToken = trim($body['numberToken']);

        try {
            $userModel = new UserModel();
            $userKyc = $userModel->findByExternalId($numberToken);
        } catch (\Throwable $e) {
            return ResponseLib::sendFail('Database error: ' . $e->getMessage(), [], 'E_DATABASE')->withStatus(500);
        }

        if ($userKyc === null) {
            return ResponseLib::sendFail('User not found for provided numberToken', [], 'E_NOT_FOUND')->withStatus(404);
        }

        $status = (int)$userKyc;
        $responsePayload = ['status' => $status];
        $logLine = sprintf('[UserCheckStatus] Responding with payload: %s', json_encode($responsePayload, JSON_UNESCAPED_SLASHES));

        if (defined('STDERR')) {
            fwrite(STDERR, $logLine . PHP_EOL);
            fflush(STDERR);
        } else {
            error_log($logLine);
        }

        return Response::json($responsePayload)->withStatus(200);
    }
}
