<?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;
use Gestoreasy\Core\Auth\MfaService;

// Prepare tenant and admin
TenantAdmin::runMigrations('default');
$pdo = ConnectionManager::forTenant('default');
TenantAdmin::seedDefaultAdmin($pdo);
$email = getenv('DEFAULT_ADMIN_EMAIL') ?: 'admin@local';
$rowAdmin = $pdo->query("SELECT id, email, name FROM users WHERE email='" . addslashes($email) . "' LIMIT 1")->fetch();
$uid = (int)($rowAdmin['id'] ?? 1);
$token = Jwt::sign(['sub' => $uid, 'email' => $rowAdmin['email'] ?? 'admin@local', 'name' => $rowAdmin['name'] ?? 'Admin', 'tenant' => 'default', 'roles' => ['admin']]);
$mfa = MfaService::issueToken($uid, 300);
$headers = ['x-tenant-id' => 'default', 'authorization' => 'Bearer ' . $token, 'x-mfa-token' => $mfa];

$kernel = new Kernel();

$body = [
  'razao_social' => 'Empresa Homolog LTDA',
  'nome' => 'Homolog',
  'cnpj' => '19131243000197',
  'email' => 'homolog@empresa.local',
  'telefone' => '(21) 1234-5678',
  'logradouro' => 'Rua das Flores',
  'numero' => '100',
  'complemento' => 'Sala 101',
  'bairro' => 'Centro',
  'cidade' => 'Rio de Janeiro',
  'estado' => 'RJ',
  'cep' => '20000000',
  'pais' => 'Brasil',
  'cert_type' => 'A3',
  'cert_password' => 'topsecret'
];

$req = new Request($headers, [], $body, [], 'PUT', '/api/settings/company');
$res = $kernel->handle($req);
fwrite(STDOUT, "Status: {$res->status}\n");
fwrite(STDOUT, "Body: " . json_encode($res->body, JSON_UNESCAPED_UNICODE) . "\n");