#!/usr/bin/env php
<?php
declare(strict_types=1);

require __DIR__ . '/../vendor/autoload.php';

use Services\TokenCreateService;

if (class_exists(Dotenv\Dotenv::class) && file_exists(__DIR__ . '/../.env')) {
    Dotenv\Dotenv::createImmutable(dirname(__DIR__), null, true)->safeLoad();
}

$dsn = $_ENV['DB_DSN'] ?? (function () {
    $host = $_ENV['DB_HOST'] ?? 'localhost';
    $port = $_ENV['DB_PORT'] ?? '5432';
    $name = $_ENV['DB_NAME'] ?? 'postgres';
    return "pgsql:host={$host};port={$port};dbname={$name}";
})();
$dbUser = $_ENV['DB_USER'] ?? 'postgres';
$dbPass = $_ENV['DB_PASSWORD'] ?? '';

$GLOBALS['pdo'] = new PDO($dsn, $dbUser, $dbPass);
$GLOBALS['pdo']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$payloadFile = $argv[1] ?? null;
$cprIdArg = $argv[1] ?? null;
if ($cprIdArg === null || !ctype_digit((string)$cprIdArg)) {
    fwrite(STDERR, "Usage: php ./test/token_create_test.php <cpr_id> [payload.json]" . PHP_EOL);
    exit(1);
}
$cprId = (int)$cprIdArg;
$payloadFile = $argv[2] ?? null;

if ($payloadFile) {
    if (!is_file($payloadFile)) {
        fwrite(STDERR, "[error] Payload file '{$payloadFile}' not found" . PHP_EOL);
        exit(1);
    }
    $data = json_decode(file_get_contents($payloadFile), true);
    if (!is_array($data)) {
        fwrite(STDERR, "[error] Invalid JSON payload" . PHP_EOL);
        exit(1);
    }
} else {
    $data = [
        'token_commodities_amount' => 1,
        'token_commodities_value' => 100,
        'token_uf' => 'SP',
        'token_city' => 'SAO PAULO',
        'token_content' => 'testetesteteste',
        'token_flag' => 'a',
        'wallet_id' => 1,
        'chain_id' => 1,
        'commodities_id' => 1,
        'cpr_id' => $cprId,
        'user_id' => 1,
    ];
}

$data['cpr_id'] = $cprId;

$required = [
    'token_commodities_amount',
    'token_commodities_value',
    'token_uf',
    'token_city',
    'token_content',
    'token_flag',
    'wallet_id',
    'chain_id',
    'commodities_id',
    'cpr_id',
    'user_id',
];

foreach ($required as $field) {
    if (!array_key_exists($field, $data)) {
        fwrite(STDERR, "[error] Missing required field: {$field}" . PHP_EOL);
        exit(1);
    }
}

$service = new TokenCreateService();

try {
    $result = $service->createToken(
        (int)$data['token_commodities_amount'],
        (int)$data['token_commodities_value'],
        (string)$data['token_uf'],
        (string)$data['token_city'],
        (string)$data['token_content'],
        (string)$data['token_flag'],
        (int)$data['wallet_id'],
        (int)$data['chain_id'],
        (int)$data['commodities_id'],
        (int)$data['cpr_id'],
        (int)$data['user_id']
    );

    echo json_encode([
        'status' => 'ok',
        'data' => $result,
    ], JSON_PRETTY_PRINT) . PHP_EOL;
} catch (Throwable $e) {
    fwrite(STDERR, '[error] ' . $e->getMessage() . PHP_EOL);
    exit(1);
}
