<?php

namespace Controllers;

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

class CommoditiesGetController
{
    public function __invoke(ServerRequestInterface $request)
    {
        $query = $request->getQueryParams();

        try {
            val::arrayVal()
                ->key('flag', val::optional(val::stringType()), false)
                ->assert($query);
        } catch (ValidationException $e) {
            return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
        }

        $flag = null;
        if (array_key_exists('flag', $query)) {
            $v = (string)$query['flag'];
            if ($v === '' || strtolower($v) === 'all') {
                $flag = null; // no filter
            } else {
                $flag = $v;
            }
        }

        $model = new CommodityModel();
        $rows = $model->getAll($flag);
        if (!$rows) {
            return ResponseLib::sendFail('Commodities Not Found', [], 'E_DATABASE')->withStatus(204);
        }
        return ResponseLib::sendOk($rows);
    }
}