<?php

namespace Controllers;

use Libs\BashExecutor;
use Libs\ResponseLib;
use Models\CompanyModel;
use Models\UserModel;
use Services\TshieldService;

use Psr\Http\Message\ServerRequestInterface;
use Respect\Validation\Validator as val;
use Respect\Validation\Exceptions\ValidationException;
use React\Http\Message\Response;

class CompanyWithUserController
{
    private CompanyModel $companyModel;
    private UserModel $userModel;
    private TshieldService $tshieldService;

    public function __construct()
    {
        $this->companyModel = new CompanyModel();
        $this->userModel = new UserModel();
        $this->tshieldService = new TshieldService();
    }

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

        try {
            val::key('company_name', val::stringType()->notEmpty()->length(1, 255))
                ->key('company_user', val::stringType()->notEmpty()->length(1, 255))
                ->key('username', val::stringType()->notEmpty()->length(1, 100))
                ->key('email', val::email())
                ->key('password', val::stringType()->length(8, null))
                ->key('phone', val::stringType()->notEmpty()->length(1, 50))
                ->key('address', val::stringType()->notEmpty()->length(1, 255))
                ->key('city', val::stringType()->notEmpty()->length(1, 100))
                ->key('state', val::stringType()->notEmpty()->length(1, 100))
                ->key('zip', val::stringType()->notEmpty()->length(1, 20))
                ->key('country', val::stringType()->notEmpty()->length(1, 100))
                ->key('kyc', val::intType(), false)
                ->key('birthdate', val::intType())
                ->key('cpf', val::stringType()->notEmpty()->length(1, 11))
                ->key('cnpj', val::stringType()->notEmpty()->length(1, 14))
                ->assert($body);
        } catch (ValidationException $e) {
            return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
        }

        try {
            $pdo = $GLOBALS['pdo'];
            $pdo->beginTransaction();

            if ($this->userModel->isEmailActive((string)$body['email'])) {
                $pdo->rollBack();
                return ResponseLib::sendFail("Email already in use", [], "E_VALIDATE")->withStatus(400);
            }

            $companyId = $this->companyModel->createCompany($body['company_name'], $body['cnpj'], 'a');
            $roleId = 1;
            $chk = $pdo->prepare('SELECT 1 FROM "role" WHERE role_id = :rid');
            $chk->execute(['rid' => $roleId]);
            if (!$chk->fetchColumn()) {
                $pdo->rollBack();
                return ResponseLib::sendFail('Default role_id 1 not found', [], 'E_DATABASE')->withStatus(500);
            }

            $userPayload = [
                'username' => $body['username'],
                'email' => $body['email'],
                'password' => $body['password'],
                'phone' => $body['phone'],
                'address' => $body['address'],
                'city' => $body['city'],
                'state' => $body['state'],
                'zip' => $body['zip'],
                'country' => $body['country'],
                'kyc' => isset($body['kyc']) ? (int)$body['kyc'] : 0,
                'birthdate' => (int)$body['birthdate'],
                'cpf' => $body['cpf'],
                'company_id' => $companyId,
                'role_id' => $roleId
            ];
            $userData = $this->userModel->createUser($userPayload);
            if (!$userData) {
                $pdo->rollBack();
                return ResponseLib::sendFail("Email already exists or creation failed", [], "E_VALIDATE")->withStatus(400);
            }

            $bin = dirname(__DIR__) . '/bin/easycli';
            $result = BashExecutor::run($bin . ' polygon create-new-address');
            if ((int)($result['exitCode'] ?? 1) !== 0) {
                $cliOutput = trim((string)($result['output'] ?? ''));
                $cliError = trim((string)($result['error'] ?? ''));
                error_log('[CompanyWithUserController] easycli wallet generation failed. Output: ' . $cliOutput . ' | Error: ' . $cliError);
                $pdo->rollBack();
                return ResponseLib::sendFail("Wallet generation failed", ['error' => $result['error'] ?? ''], "E_INTERNAL")->withStatus(500);
            }
            $output = trim((string)($result['output'] ?? ''));

            $parsed = [];
            foreach (preg_split('/\r?\n/', $output) as $line) {
                $line = trim($line);
                if ($line === '' || strpos($line, '=') === false) { continue; }
                [$k, $v] = explode('=', $line, 2);
                $parsed[trim($k)] = trim($v);
            }
            if (!isset($parsed['privateKey'], $parsed['publicKey'], $parsed['address'])) {
                $pdo->rollBack();
                return ResponseLib::sendFail("Wallet parsing failed", ['raw' => $output], "E_INTERNAL")->withStatus(500);
            }

            $stmt = $pdo->prepare('SELECT chain_id FROM "chain" WHERE chain_name = :name');
            $stmt->execute(['name' => 'polygon']);
            $chainId = $stmt->fetchColumn();
            if (!$chainId) {
                $pdo->rollBack();
                return ResponseLib::sendFail("Chain not found", [], "E_DATABASE")->withStatus(500);
            }

            $stmt = $pdo->prepare('INSERT INTO "wallet" (company_id, wallet_public_key, wallet_address, wallet_private_key, wallet_flag, chain_id) VALUES (:company_id, :public_key, :address, :private_key, :flag, :chain_id) RETURNING wallet_id');
            $stmt->execute([
                'company_id' => $companyId,
                'public_key' => $parsed['publicKey'],
                'address' => $parsed['address'],
                'private_key' => $parsed['privateKey'],
                'flag' => 'a',
                'chain_id' => (int)$chainId
            ]);
            $walletId = (int)$stmt->fetchColumn();

            $pdo->commit();

            $analysisPayload = [
                'corporate_name' => $body['company_user'],
                'cnpj' => $body['cnpj'],
            ];

            error_log(sprintf(
                '[CompanyWithUserController] Sending company_user="%s" with analysis payload: %s',
                $body['company_user'],
                json_encode($analysisPayload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
            ));

            try {
                $tshield = $this->tshieldService->generateCompanyLink(
                    (int)$userData['user_id'],
                    $analysisPayload
                );
            } catch (\Throwable $e) {
                return ResponseLib::sendFail('TShield link generation failed: ' . $e->getMessage(), [], 'E_EXTERNAL')->withStatus(502);
            }

            $payload = [
                'status' => 'ok',
                'link' => $tshield['link'],
                'numberToken' => $tshield['number'],
                'data' => [
                    'link' => $tshield['link'],
                    'numberToken' => $tshield['number'],
                    'tshield' => $tshield,
                ]
            ];

            return Response::json($payload)->withStatus(201);

        } catch (\Throwable $e) {
            if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollBack(); }
            return ResponseLib::sendFail($e->getMessage(), [], 'E_DATABASE')->withStatus(500);
        }
    }
}