<?php

namespace Controllers;

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

class TokenGetController
{
    private TokenModel $model;

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

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

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

        $uf = (string)$body['token_uf'];
        $commoditiesName = (string)$body['commodities_name'];
        $tokens = $this->model->getByUfAndCommodityName($uf, $commoditiesName);

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