<?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 CommodityDeleteController
{
    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())
                ->assert($body);
        } catch (ValidationException $e) {
            return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
        }

        $id = (int)$body['commodities_id'];

        $deleted = $this->model->delete($id);

        return $deleted
            ? ResponseLib::sendOk(['deleted' => true], 'S_DELETED')
            : ResponseLib::sendFail('Commodity Not Found', [], 'E_DATABASE')->withStatus(204);
    }
}