<?php
use Gestoreasy\Core\Kernel;
use Gestoreasy\Core\Http\Request;
use Gestoreasy\Core\Auth\Jwt;
use Gestoreasy\Core\Tenant\TenantAdmin;
use Gestoreasy\Core\Tenant\ConnectionManager;

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

function assertTrue($cond, $msg) { if (!$cond) { throw new Exception($msg); } }

$kernel = new Kernel();
$tenant = (getenv('TEST_TENANT') ?: 'default');
TenantAdmin::runMigrations($tenant);
$token = Jwt::sign(['sub' => 1, 'email' => 'admin@local', 'name' => 'Admin', 'tenant' => $tenant, 'roles' => ['admin']]);
$auth = ['authorization' => 'Bearer ' . $token, 'x-tenant-id' => $tenant];

// Preparar produtos
$pdo = ConnectionManager::forTenant($tenant);
// Garantir tabela products tem campos utilizados
try {
  $pdo->exec("CREATE TABLE IF NOT EXISTS products (
    id INTEGER PRIMARY KEY AUTO_INCREMENT,
    codigo VARCHAR(100) NULL,
    descricao VARCHAR(190) NULL,
    estoque NUMERIC(14,3) NULL DEFAULT 0
  )");
} catch (\Throwable $e) {}
// Inserir dois produtos
$pdo->exec("INSERT INTO products (codigo, descricao, estoque) VALUES ('SKU-A','Prod A', 5)");
$aId = (int)$pdo->lastInsertId();
$pdo->exec("INSERT INTO products (codigo, descricao, estoque) VALUES ('SKU-B','Prod B', 200)");
$bId = (int)$pdo->lastInsertId();

// Definir thresholds via API
$reqSetA = new Request($auth, [], ['product_id' => $aId, 'min_stock' => 10, 'max_stock' => 0, 'alert_enabled' => 1, 'notify_email' => 'stock@test.local'], [], 'POST', '/api/estoque/thresholds');
$resSetA = $kernel->handle($reqSetA);
assertTrue(($resSetA->status ?? 0) === 200, 'Definir threshold A deve retornar 200');

$reqSetB = new Request($auth, [], ['product_id' => $bId, 'min_stock' => 0, 'max_stock' => 100, 'alert_enabled' => 1], [], 'POST', '/api/estoque/thresholds');
$resSetB = $kernel->handle($reqSetB);
assertTrue(($resSetB->status ?? 0) === 200, 'Definir threshold B deve retornar 200');

// Listar thresholds
$reqList = new Request($auth, [], [], [], 'GET', '/api/estoque/thresholds');
$resList = $kernel->handle($reqList);
assertTrue(($resList->status ?? 0) === 200, 'Listar thresholds deve retornar 200');
$rows = (array)($resList->body['data'] ?? []);
assertTrue(count($rows) >= 2, 'Deve listar ao menos 2 registros');
$rowA = null; $rowB = null;
foreach ($rows as $r) {
  if ((int)($r['product_id'] ?? 0) === $aId) $rowA = $r;
  if ((int)($r['product_id'] ?? 0) === $bId) $rowB = $r;
}
assertTrue(!!$rowA && !!$rowB, 'Registros A e B devem existir');
assertTrue(($rowA['product_code'] ?? '') === 'SKU-A', 'A: product_code deve ser SKU-A');
assertTrue(($rowB['product_name'] ?? '') === 'Prod B', 'B: product_name deve ser Prod B');
assertTrue((int)($rowA['alert_enabled'] ?? 0) === 1, 'A: alert_enabled=1');

// Consultar alertas
$reqAlerts = new Request($auth, [], [], [], 'GET', '/api/estoque/alertas');
$resAlerts = $kernel->handle($reqAlerts);
assertTrue(($resAlerts->status ?? 0) === 200, 'Alertas deve retornar 200');
$alerts = (array)($resAlerts->body['data'] ?? []);
$hasBelowA = false; $hasAboveB = false;
foreach ($alerts as $a) {
  if ((int)($a['product_id'] ?? 0) === $aId && ($a['type'] ?? '') === 'below_min') $hasBelowA = true;
  if ((int)($a['product_id'] ?? 0) === $bId && ($a['type'] ?? '') === 'above_max') $hasAboveB = true;
}
assertTrue($hasBelowA, 'A deve estar abaixo do mínimo');
assertTrue($hasAboveB, 'B deve estar acima do máximo');

// Relatório
$reqReport = new Request($auth, [], [], [], 'GET', '/api/estoque/thresholds/report');
$resReport = $kernel->handle($reqReport);
assertTrue(($resReport->status ?? 0) === 200, 'Relatório deve retornar 200');
$dataRep = (array)($resReport->body['data'] ?? []);
$below = (array)($dataRep['below_min'] ?? []);
$above = (array)($dataRep['above_max'] ?? []);
assertTrue(count($below) >= 1, 'Relatório: pelo menos 1 abaixo do mínimo');
assertTrue(count($above) >= 1, 'Relatório: pelo menos 1 acima do máximo');

echo "InventoryThresholdsTest: OK\n";