<?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 CommodityUpdateController
{
    private CommodityModel $model;

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

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

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

        $id = (int)$body['commodities_id'];
        $name = array_key_exists('name', $body) ? trim($body['name']) : null;
        $flag = array_key_exists('flag', $body) ? $body['flag'] : null;

        if ($name === null && $flag === null) {
            return ResponseLib::sendFail('Validation failed: nothing to update', [], 'E_VALIDATE')->withStatus(400);
        }

        $updated = $this->model->update($id, $name, $flag);
        if (!$updated) {
            return ResponseLib::sendFail('Commodity Not Found or Not Updated', [], 'E_DATABASE')->withStatus(204);
        }
        return ResponseLib::sendOk($updated, 'S_UPDATED');
    }
}