<?php
// Integration test for Google Calendar (mock mode)

function httpJson($method, $url, $body = null, $headers = []) {
    $ctxHeaders = [];
    foreach ($headers as $k => $v) { $ctxHeaders[] = $k . ': ' . $v; }
    $opts = [ 'http' => [ 'method' => $method, 'ignore_errors' => true, 'header' => implode("\r\n", $ctxHeaders) ] ];
    if ($body !== null) { $opts['http']['content'] = json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); }
    $ctx = stream_context_create($opts);
    $res = @file_get_contents($url, false, $ctx);
    $status = 0; global $http_response_header; if (is_array($http_response_header)) { foreach ($http_response_header as $h) { if (preg_match('/^HTTP\/[0-9\.]+\s+(\d+)/', $h, $m)) { $status = (int)$m[1]; break; } } }
    $json = null; if ($res !== false && $res !== null && $res !== '') { $json = json_decode($res, true); }
    return [ 'status' => $status, 'json' => $json, 'raw' => $res ];
}

$base = 'http://localhost:8003';
$tenant = 'default';

// 1) Seed admin
$seed = httpJson('POST', $base . '/api/auth/seed-admin', [ 'email' => 'admin@local', 'password' => 'admin123', 'name' => 'Admin' ], [ 'Content-Type' => 'application/json', 'x-tenant-id' => $tenant ]);
if (!in_array($seed['status'], [200,201,409], true)) { fwrite(STDERR, "seed-admin falhou: status {$seed['status']}\n" ); }

// 2) Login
$login = httpJson('POST', $base . '/api/auth/login', [ 'email' => 'admin@local', 'password' => 'admin123' ], [ 'Content-Type' => 'application/json', 'x-tenant-id' => $tenant ]);
if ($login['status'] !== 200 || empty($login['json']['access_token'])) { fwrite(STDERR, "login falhou: status {$login['status']} body={$login['raw']}\n" ); exit(1); }
$token = $login['json']['access_token'];
$authHdrs = [ 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $token, 'x-tenant-id' => $tenant ];

// 3) Salvar config Google
$cfg = httpJson('POST', $base . '/api/integrations/google-calendar/config', [ 'calendar_id' => 'primary', 'client_id' => 'dummy', 'client_secret' => 'dummy', 'refresh_token' => 'dummy' ], $authHdrs);
if (!in_array($cfg['status'], [200,201], true)) { fwrite(STDERR, "saveConfig google falhou: status {$cfg['status']} body={$cfg['raw']}\n" ); exit(1); }

// 4) Criar evento pontual
$start = (new DateTime('+1 day'))->format('Y-m-d\TH:i:00');
$end = (new DateTime('+1 day +1 hour'))->format('Y-m-d\TH:i:00');
$evt = httpJson('POST', $base . '/api/integrations/google-calendar/events', [ 'summary' => 'Lembrete Teste', 'description' => 'Teste de integração', 'start' => $start, 'end' => $end, 'reminder_minutes' => 30 ], $authHdrs);
if ($evt['status'] !== 201 || empty($evt['json']['data']['id'])) { fwrite(STDERR, "createEvent falhou: status {$evt['status']} body={$evt['raw']}\n" ); exit(1); }

// 5) Rodar sincronização de contas a pagar (resultado pode ser zero)
$sync = httpJson('POST', $base . '/api/integrations/google-calendar/sync/payables', [ 'reminder_minutes' => 60 ], $authHdrs);
if ($sync['status'] !== 200 || empty($sync['json']['ok'])) { fwrite(STDERR, "syncPayables falhou: status {$sync['status']} body={$sync['raw']}\n" ); exit(1); }

echo "OK GoogleCalendarSyncTest\n";