<?php

namespace Controllers;

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

class OrderbookPaymentController
{
    private OrderbookPaymentModel $orderbookPaymentModel;
    private PaymentService $paymentService;

    public function __construct()
    {
        $this->orderbookPaymentModel = new OrderbookPaymentModel();
        $this->paymentService = new PaymentService();
    }

    public function __invoke(ServerRequestInterface $request)
    {
        $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'];

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

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

        if ((int)$order['status_id'] !== OrderbookModel::STATUS_OPEN) {
            return ResponseLib::sendFail('Orderbook não está disponível para pagamento', ['orderbook_id' => $orderbookId, 'status_id' => $order['status_id']], 'E_ORDERBOOK_STATUS')->withStatus(409);
        }

        $tokenValue = (float)($order['token_commodities_value'] ?? 0);
        if ($tokenValue <= 0) {
            return ResponseLib::sendFail('Valor do token inválido', ['orderbook_id' => $orderbookId], 'E_TOKEN_VALUE')->withStatus(422);
        }

        $tokenExternalId = trim((string)($order['token_external_id'] ?? ''));
        if ($tokenExternalId === '') {
            return ResponseLib::sendFail('Orderbook sem token externo associado', ['orderbook_id' => $orderbookId], 'E_TOKEN_NOT_FOUND')->withStatus(409);
        }

        $paymentFlag = sprintf('orderbook:%d;token:%s', $orderbookId, $tokenExternalId);

        try {
            $paymentData = $this->paymentService->initiatePayment((int)round($tokenValue * 100), $paymentFlag);
        } catch (\Throwable $e) {
            return ResponseLib::sendFail('Falha ao iniciar pagamento: ' . $e->getMessage(), [], 'E_PAYMENT')->withStatus(500);
        }

        return ResponseLib::sendOk([
            'orderbook_id' => $orderbookId,
            'payment_id' => $paymentData['payment_id'],
            'payment_code' => $paymentData['payment_code'],
            'payment_external_id' => $paymentData['payment_external_id'],
            'token_external_id' => $tokenExternalId,
        ], 'S_ORDERBOOK_PAYMENT');
    }
}
