<?php

namespace Controllers;

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

class OrderbookUpdateStatusController
{
    private OrderbookModel $orderbookModel;

    public function __construct()
    {
        $this->orderbookModel = new OrderbookModel();
    }

    public function __invoke(ServerRequestInterface $request)
    {
        $companyId = (int)($request->getAttribute('api_company_id') ?? 0);
        if ($companyId <= 0) {
            return ResponseLib::sendFail('Empresa autenticada não encontrada', [], 'E_VALIDATE')->withStatus(401);
        }

        $body = json_decode((string)$request->getBody(), true) ?? [];

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

        $orderbookId = (int)$body['orderbook_id'];
        $statusId = 3;

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

        if (!$orderbook) {
            return ResponseLib::sendFail('Orderbook não encontrado', ['orderbook_id' => $orderbookId], 'E_NOT_FOUND')->withStatus(404);
        }

        $orderCompanyId = (int)($orderbook['company_id'] ?? 0);
        if ($orderCompanyId <= 0 || $orderCompanyId !== $companyId) {
            return ResponseLib::sendFail('Orderbook não pertence à empresa autenticada', ['orderbook_id' => $orderbookId], 'E_FORBIDDEN')->withStatus(403);
        }

        try {
            $this->orderbookModel->updateStatus($orderbookId, $statusId);
        } catch (\Throwable $e) {
            return ResponseLib::sendFail('Falha ao atualizar status do orderbook: ' . $e->getMessage(), [], 'E_DATABASE')->withStatus(500);
        }

        return ResponseLib::sendOk([
            'orderbook_id' => $orderbookId,
            'status_id' => $statusId,
        ], 'S_ORDERBOOK_STATUS_UPDATED');
    }
}
