<?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 UserGetController
{
    private UserModel $model;

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

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

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

        $companyId = (int) $body['company_id'];
        $users = $this->model->getUsersByCompany($companyId);

        return $users
            ? ResponseLib::sendOk($users)
            : ResponseLib::sendFail("User Not Found", [], "E_DATABASE")->withStatus(204);
    }
}