<?php
require_once __DIR__ . '/../bootstrap.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;

function assertTrue($cond, $msg) { if (!$cond) { echo "FAIL: $msg\n"; exit(1); } }

$tenant = $argv[1] ?? 'default';
TenantAdmin::runMigrations($tenant);
$pdo = ConnectionManager::forTenant($tenant);

// 1) Semear cliente necessário para pedidos
$stmt = $pdo->prepare("INSERT INTO clients (nome, cnpj, created_at) VALUES (?, ?, ?)");
$stmt->execute(['Cliente Comissoes', '00.111.222/0001-33', date('Y-m-d H:i:s')]);
$clientId = (int)$pdo->lastInsertId();
assertTrue($clientId > 0, 'Cliente criado deve ter id > 0');

// 2) Semear usuário (vendedor) e vendedor com comissão
$uniqueEmail = 'seller+' . substr((string)mt_rand(1000, 999999), 0, 6) . '@example.test';
$stmt = $pdo->prepare("INSERT INTO users (email, name, password_hash, created_at) VALUES (?, ?, ?, ?)");
$stmt->execute([$uniqueEmail, 'Seller Test', '$2y$10$abcdefghijklmnopqrstuv', date('Y-m-d H:i:s')]);
$userId = (int)$pdo->lastInsertId();
assertTrue($userId > 0, 'Usuário criado deve ter id > 0');

$stmt = $pdo->prepare("INSERT INTO vendedores (nome, email, comissao_percent, created_at) VALUES (?, ?, ?, ?)");
$stmt->execute(['Seller Test', $uniqueEmail, 10.00, date('Y-m-d H:i:s')]);
$vendId = (int)$pdo->lastInsertId();
assertTrue($vendId > 0, 'Vendedor criado deve ter id > 0');

// 3) Criar pedido simples e log de auditoria de criação vinculado ao usuário
$numero = 'SO-' . substr((string)mt_rand(1000, 999999), 0, 6);
$stmt = $pdo->prepare("INSERT INTO sales_orders (numero, cliente_id, valor_total, status, created_at) VALUES (?, ?, ?, ?, ?)");
$stmt->execute([$numero, $clientId, 100.00, 'aberto', date('Y-m-d H:i:s')]);
$orderId = (int)$pdo->lastInsertId();
assertTrue($orderId > 0, 'Pedido criado deve ter id > 0');

$stmt = $pdo->prepare("INSERT INTO audit_logs (user_id, action, resource, resource_id, new_data, created_at) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->execute([$userId, 'create', 'sales_orders', $orderId, json_encode(['id' => $orderId]), date('Y-m-d H:i:s')]);

// 4) Chamar endpoint com token e validar resposta
$payload = [
    'sub' => $userId,
    'email' => $uniqueEmail,
    'name' => 'Seller Test',
    'tenant' => $tenant,
    'roles' => ['admin'],
    // Bypass de RBAC para testes
    'impersonated' => true
];
$token = Jwt::sign($payload);
$authHeaders = [
    'x-tenant-id' => $tenant,
    'authorization' => 'Bearer ' . $token
];

$kernel = new Kernel();
$today = date('Y-m-d');
$start = date('Y-m-d', strtotime('-1 day'));
$req = new Request($authHeaders, ['start' => $start, 'end' => $today], [], [], 'GET', '/api/vendas/comissoes/by-seller');
$res = $kernel->handle($req);
assertTrue($res->status === 200, 'GET /api/vendas/comissoes/by-seller deve retornar 200');

$data = $res->body['data'] ?? [];
assertTrue(is_array($data) && count($data) >= 1, 'Resposta deve conter pelo menos um vendedor');

$found = false; $revOk = false; $commOk = false;
foreach ($data as $row) {
    if (strtolower((string)($row['seller_email'] ?? '')) === strtolower($uniqueEmail)) {
        $found = true;
        $revOk = ((int)($row['revenue_cents'] ?? 0)) === 10000; // 100.00 -> 10000 cents
        $commOk = ((int)($row['commission_cents'] ?? 0)) === 1000; // 10% de 100.00
        break;
    }
}
assertTrue($found, 'Entrada do vendedor esperado deve estar na resposta');
assertTrue($revOk, 'Receita em cents deve ser 10000');
assertTrue($commOk, 'Comissão em cents deve ser 1000');

echo "PASS: SalesCommissionsBySellerTest — shape e cálculo OK.\n";