<?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); } }

// Setup kernel and auth headers
$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']]);
$authHeaders = ['authorization' => 'Bearer ' . $token, 'x-tenant-id' => $tenant];

// 1) Criar fornecedor e produto mínimos
$supplierId = 0; $productId = 0;
{
  $db = ConnectionManager::forTenant($tenant);
  $db->exec("INSERT INTO suppliers (nome, email) VALUES ('Fornecedor Exp', 'exp@test.local')");
  $supplierId = (int)$db->lastInsertId();
  $db->exec("INSERT INTO products (codigo, descricao, preco) VALUES ('SKU-EXP','Produto Exp', 1.00)");
  $productId = (int)$db->lastInsertId();
}

// 2) Criar cotação com validade passada
$yesterday = date('Y-m-d', strtotime('-1 day'));
$quoteBody = [
  'supplier_id' => $supplierId,
  'valid_until' => $yesterday,
  'status' => 'open',
  'items' => [ [ 'product_id' => $productId, 'quantity' => 1, 'price' => 1.00 ] ]
];
$reqQuote = new Request($authHeaders, [], $quoteBody, [], 'POST', '/api/compras/cotacoes');
$resQuote = $kernel->handle($reqQuote);
assertTrue(($resQuote->status ?? 0) === 201 || ($resQuote->status ?? 0) === 200, 'Criar cotação deve retornar 201/200');
$quoteId = (int)($resQuote->body['data']['id'] ?? 0);
assertTrue($quoteId > 0, 'Cotação criada deve ter id');

// 3) Enviar convite
$reqInv = new Request($authHeaders, [], ['supplier_id' => $supplierId], [], 'POST', "/api/compras/cotacoes/{$quoteId}/enviar-convite");
$reqInv->set('params', [$quoteId]);
$resInv = $kernel->handle($reqInv);
assertTrue(($resInv->status ?? 0) === 200, 'Enviar convite deve retornar 200');
$token = (string)($resInv->body['data']['token'] ?? '');
// Debug: validade retornada pelo convite
if (isset($resInv->body['data']['valid_until'])) { echo "Invite valid_until: ".$resInv->body['data']['valid_until']."\n"; }
assertTrue($token !== '', 'Resposta de convite deve conter token');

// 4) Tentar abrir link (deve expirar)
$reqTok = new Request(['x-tenant-id' => $authHeaders['x-tenant-id']], ['token' => $token], [], [], 'GET', '/api/compras/cotacoes/responder');
$resTok = $kernel->handle($reqTok);
// Debug: status ao abrir link
echo "Open status: ".$resTok->status."\n";
assertTrue(($resTok->status ?? 0) === 410, 'Link expirado deve retornar 410');
assertTrue(($resTok->body['error'] ?? '') === 'link_expired', 'Erro deve ser link_expired');

// 5) Listar convites e verificar effective_status = failed
$reqList = new Request($authHeaders, [], [], [], 'GET', "/api/compras/cotacoes/{$quoteId}/convites-respostas");
$reqList->set('params', [$quoteId]);
$resList = $kernel->handle($reqList);
assertTrue(($resList->status ?? 0) === 200, 'Listar convites deve retornar 200');
$invites = $resList->body['data']['invites'] ?? [];
assertTrue(is_array($invites) && count($invites) >= 1, 'Deve haver ao menos um convite');
$effStatus = (string)($invites[0]['effective_status'] ?? '');
assertTrue($effStatus === 'failed', 'Convite expirado deve ter effective_status=failed');

echo "InviteExpirationTest: OK\n";