<?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;

class UserInfoController
{
    private UserModel $model;

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

    public function __invoke(ServerRequestInterface $request)
    {
        $companyId = (int)($request->getAttribute('api_company_id') ?? 0);
        if ($companyId <= 0) {
            return ResponseLib::sendFail('Authenticated company not found', [], 'E_VALIDATE')->withStatus(401);
        }

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

        try {
            val::key('user_id', val::intType()->positive())
                ->assert($body);
        } catch (ValidationException $e) {
            return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
        }

        $userId = (int)$body['user_id'];

        $row = $this->model->getUserInfoById($userId, $companyId);
        if (!$row) {
            return ResponseLib::sendFail('User Not Found', [], 'E_DATABASE')->withStatus(204);
        }

        $data = [
            'id' => (int)($row['user_id'] ?? 0),
            'nome' => $row['user_name'] ?? null,
            'email' => $row['user_email'] ?? null,
            'telefone' => $row['user_phone'] ?? null,
            'cpf' => $row['user_cpf'] ?? null,
            'dataNasc' => isset($row['user_birthdate']) ? (int)$row['user_birthdate'] : null,
            'kyc' => isset($row['user_kyc']) ? (int)$row['user_kyc'] : null,
            'roleId' => isset($row['role_id']) ? (int)$row['role_id'] : null,
            'status' => $row['user_flag'] ?? null,
            'endereco' => $row['user_address'] ?? null,
            'cidade' => $row['user_city'] ?? null,
            'estado' => $row['user_state'] ?? null,
            'cep' => $row['user_zip'] ?? null,
            'pais' => $row['user_country'] ?? null,
        ];

        return ResponseLib::sendOk($data);
    }
}
