<?php

namespace Controllers;

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

class OrderbookFilterController
{
    private OrderbookSearchModel $searchModel;

    public function __construct()
    {
        $this->searchModel = new OrderbookSearchModel();
    }

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

        try {
            val::key('state', val::stringType()->notEmpty())
                ->key('commodity_type', val::stringType()->notEmpty())
                ->assert($body);
        } catch (ValidationException $e) {
            return ResponseLib::sendFail(
                'Validation failed: ' . $e->getFullMessage(),
                [],
                'E_VALIDATE'
            )->withStatus(400);
        }

        $state = strtoupper(trim((string)$body['state']));
        $commodityType = trim((string)$body['commodity_type']);

        try {
            $orders = $this->searchModel->searchOpenOrders($state, $commodityType);
        } catch (\Throwable $e) {
            return ResponseLib::sendFail(
                'Falha ao consultar orderbook: ' . $e->getMessage(),
                [],
                'E_DATABASE'
            )->withStatus(500);
        }

        $companyId = (int)($request->getAttribute('api_company_id') ?? 0);

        if (!$orders) {
            return ResponseLib::sendOk(
                [
                    'state' => $state,
                    'commodity_type' => $commodityType,
                    'orders' => [],
                ],
                'S_ORDERBOOK_EMPTY'
            );
        }

        $orders = array_map(static function (array $order) use ($companyId) {
            $orderCompanyId = isset($order['company_id']) ? (int)$order['company_id'] : null;
            $order['editable'] = $companyId > 0 && $orderCompanyId === $companyId;
            unset($order['company_id']);
            return $order;
        }, $orders);

        return ResponseLib::sendOk([
            'state' => $state,
            'commodity_type' => $commodityType,
            'orders' => $orders,
        ], 'S_ORDERBOOK_FILTER');
    }
}
