<?php
require_once __DIR__ . '/../bootstrap.php';

use Gestoreasy\Core\Kernel;
use Gestoreasy\Core\Http\Request;
use Gestoreasy\Core\Auth\Jwt;
use Gestoreasy\Core\Tenant\ConnectionManager;

$kernel = new Kernel();

$payload = [
    'sub' => 1,
    'email' => 'admin@local',
    'name' => 'Admin',
    'tenant' => 'default',
    'roles' => ['admin']
];
$token = Jwt::sign($payload);
$authHeaders = [
    'x-tenant-id' => 'default',
    'authorization' => 'Bearer ' . $token
];

// Cria produto
$bodyCreate = [
    'codigo' => 'DEBUG-SKU-001',
    'ean' => '7890000000000',
    'ncm' => '12345678',
    'cfop' => '5102',
    'preco' => 10.50
];
$reqCreate = new Request($authHeaders, [], $bodyCreate, [], 'POST', '/api/produtos');
$resCreate = $kernel->handle($reqCreate);
echo "create status: {$resCreate->status}\n";
var_dump($resCreate->body);
$newId = (int)($resCreate->body['id'] ?? 0);

// Tenta salvar meta
$meta = ['nome' => 'Produto Debug', 'marca' => 'X'];
$reqMeta = new Request($authHeaders, [], $meta, [], 'POST', "/api/produtos/$newId/meta");
$resMeta = $kernel->handle($reqMeta);
echo "meta status: {$resMeta->status}\n";
var_dump($resMeta->body);

// Verifica se tabela product_meta existe e listar schema_migrations
try {
    $pdo = ConnectionManager::forTenant();
    $chk = $pdo->query("SHOW TABLES LIKE 'product_meta'");
    $exists = $chk->fetch() ? true : false;
    echo "product_meta exists: " . ($exists ? 'yes' : 'no') . "\n";
    $rows = $pdo->query('SELECT module, filename, applied_at FROM schema_migrations ORDER BY module, filename')->fetchAll();
    echo "\nMigrations applied:\n";
    foreach ($rows as $row) {
        echo ($row['module'] ?? '?') . ' - ' . ($row['filename'] ?? '?') . "\n";
    }
} catch (\Throwable $e) {
    echo "check error: " . $e->getMessage() . "\n";
}