<?php

namespace Controllers;

use Libs\ResponseLib;
use Models\CprModel;
use Models\OrderbookModel;
use Models\OrderbookTransferModel;
use Models\PaymentModel;
use Models\TokenModel;
use Models\WalletModel;
use Psr\Http\Message\ServerRequestInterface;
use Respect\Validation\Exceptions\ValidationException;
use Respect\Validation\Validator as val;
use Services\TokenTransferService;

class OrderbookTransferController
{
    private PaymentModel $paymentModel;
    private WalletModel $walletModel;
    private OrderbookTransferModel $orderbookTransferModel;
    private TokenTransferService $tokenTransferService;
    private TokenModel $tokenModel;
    private CprModel $cprModel;
    private OrderbookModel $orderbookModel;
    private \PDO $pdo;

    public function __construct()
    {
        if (!isset($GLOBALS['pdo']) || !$GLOBALS['pdo'] instanceof \PDO) {
            throw new \RuntimeException('Global PDO connection not initialized');
        }

        $this->pdo = $GLOBALS['pdo'];
        $this->paymentModel = new PaymentModel();
        $this->walletModel = new WalletModel();
        $this->orderbookTransferModel = new OrderbookTransferModel();
        $this->tokenTransferService = new TokenTransferService();
        $this->tokenModel = new TokenModel();
        $this->cprModel = new CprModel();
        $this->orderbookModel = new OrderbookModel();
    }

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

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

        $externalId = trim((string)$body['external_id']);
        $tokenExternalId = trim((string)$body['token_external_id']);
        $companyId = (int)($request->getAttribute('api_company_id') ?? 0);

        if ($companyId <= 0) {
            return ResponseLib::sendFail('Empresa autenticada não encontrada', [], 'E_VALIDATE')->withStatus(401);
        }

        try {
            $payment = $this->paymentModel->findByExternalId($externalId);
        } catch (\Throwable $e) {
            return ResponseLib::sendFail('Falha ao consultar pagamento: ' . $e->getMessage(), [], 'E_DATABASE')->withStatus(500);
        }

        if (!$payment) {
            return ResponseLib::sendFail('Pagamento não encontrado', ['external_id' => $externalId], 'E_NOT_FOUND')->withStatus(404);
        }

        if ((int)$payment['status_id'] !== PaymentModel::STATUS_COMPLETED) {
            return ResponseLib::sendFail('Pagamento ainda não concluído', ['external_id' => $externalId, 'status_id' => $payment['status_id']], 'E_PAYMENT_PENDING')->withStatus(409);
        }

        try {
            $orderbook = $this->orderbookTransferModel->getByTokenExternalId($tokenExternalId);
        } 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', ['token_external_id' => $tokenExternalId], 'E_NOT_FOUND')->withStatus(404);
        }

        if ((int)$orderbook['status_id'] !== OrderbookModel::STATUS_OPEN) {
            if ((int)$orderbook['status_id'] === OrderbookModel::STATUS_COMPLETED) {
                return ResponseLib::sendOk([
                    'orderbook_id' => (int)$orderbook['orderbook_id'],
                    'token_external_id' => $tokenExternalId,
                    'message' => 'Orderbook já transferido anteriormente',
                ], 'S_TOKEN_ALREADY_TRANSFERRED');
            }

            return ResponseLib::sendFail(
                'Orderbook não está disponível para transferência',
                ['orderbook_id' => (int)$orderbook['orderbook_id'], 'status_id' => $orderbook['status_id']],
                'E_ORDERBOOK_STATUS'
            )->withStatus(409);
        }

        $paymentFlag = trim((string)($payment['payment_flag'] ?? ''));
        $expectedFlag = sprintf('orderbook:%d;token:%s', (int)$orderbook['orderbook_id'], $tokenExternalId);
        if ($paymentFlag === '' || $paymentFlag !== $expectedFlag) {
            return ResponseLib::sendFail(
                'Pagamento não vinculado ao orderbook informado',
                [
                    'external_id' => $externalId,
                    'payment_flag' => $paymentFlag,
                    'expected' => $expectedFlag,
                ],
                'E_PAYMENT_MISMATCH'
            )->withStatus(409);
        }

        $tokenId = (int)($orderbook['token_id'] ?? 0);
        if ($tokenId <= 0) {
            return ResponseLib::sendFail('Orderbook sem token associado', [], 'E_ORDERBOOK_TOKEN')->withStatus(409);
        }

        try {
            $token = $this->tokenModel->findById($tokenId);
        } catch (\Throwable $e) {
            return ResponseLib::sendFail('Falha ao carregar token vinculado: ' . $e->getMessage(), [], 'E_DATABASE')->withStatus(500);
        }

        if (!$token) {
            return ResponseLib::sendFail('Token associado ao orderbook não encontrado', ['token_id' => $tokenId], 'E_TOKEN_NOT_FOUND')->withStatus(404);
        }

        $cprId = (int)($token['cpr_id'] ?? 0);
        if ($cprId <= 0) {
            return ResponseLib::sendFail('Token não está vinculado a uma CPR', ['token_id' => $tokenId], 'E_CPR_NOT_FOUND')->withStatus(409);
        }

        try {
            $wallet = $this->walletModel->getPrimaryWalletByCompanyId($companyId);
        } catch (\Throwable $e) {
            return ResponseLib::sendFail('Falha ao consultar carteira da empresa: ' . $e->getMessage(), [], 'E_DATABASE')->withStatus(500);
        }

        if (!$wallet || empty($wallet['wallet_address'])) {
            return ResponseLib::sendFail('Carteira da empresa não encontrada', [], 'E_WALLET_NOT_FOUND')->withStatus(404);
        }

        $serverAddress = $this->resolveServerAddress();

        try {
            $transferResult = $this->tokenTransferService->transferFrom($serverAddress, (string)$wallet['wallet_address'], $tokenExternalId);
        } catch (\Throwable $e) {
            return ResponseLib::sendFail('Falha ao transferir token: ' . $e->getMessage(), [], 'E_TRANSFER')->withStatus(500);
        }

        $txHash = $transferResult['tx_hash'] ?? null;
        if (!$txHash) {
            return ResponseLib::sendFail('Transferência não retornou hash válido', [], 'E_TRANSFER_HASH')->withStatus(502);
        }

        try {
            $this->pdo->beginTransaction();

            $this->orderbookModel->updateWalletId((int)$orderbook['orderbook_id'], (int)$wallet['wallet_id']);
            $this->orderbookTransferModel->markCompleted((int)$orderbook['orderbook_id']);
            $this->tokenModel->updateWalletId($tokenId, (int)$wallet['wallet_id']);
            $this->cprModel->updateCompanyId($cprId, $companyId);

            $this->pdo->commit();
        } catch (\Throwable $e) {
            if ($this->pdo->inTransaction()) {
                $this->pdo->rollBack();
            }

            return ResponseLib::sendFail(
                'Falha ao atualizar registros após transferência: ' . $e->getMessage(),
                [],
                'E_TRANSFER_PERSIST'
            )->withStatus(500);
        }

        return ResponseLib::sendOk([
            'orderbook_id' => (int)$orderbook['orderbook_id'],
            'token_external_id' => $tokenExternalId,
            'destination_address' => (string)$wallet['wallet_address'],
            'transfer_output' => $transferResult['output'] ?? '',
            'transfer_error' => $transferResult['error'] ?? '',
            'transaction_hash' => $txHash,
        ], 'S_TOKEN_TRANSFERRED');
    }

    private function resolveServerAddress(): string
    {
        $address = $_ENV['SERVER_WALLET_ADDRESS'] ?? $_ENV['EASY_ADMIM_PUBLIC_KEY'] ?? '';
        $trimmed = trim((string)$address);
        if ($trimmed === '') {
            throw new \RuntimeException('Endereço do servidor (SERVER_WALLET_ADDRESS) não configurado.');
        }

        return $trimmed;
    }
}
