<?php
// tests/test-meta.php — Verify meta-data.php response has required fields
require_once __DIR__ . '/run.php';

$base    = defined('TEST_BASE_URL') ? TEST_BASE_URL : 'http://localhost/supercerebro';
$session = defined('TEST_SESSION_COOKIE') ? TEST_SESSION_COOKIE : '';

if (!$session) {
    dm_skip('test-meta', 'TEST_SESSION_COOKIE not set — skipping authenticated tests');
    return;
}

$ch = curl_init("{$base}/api/meta-data.php?action=overview&client_id=1&period=30d");
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 20,
    CURLOPT_HTTPHEADER     => ["Cookie: {$session}"],
]);
$raw  = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

dm_assert('meta-data HTTP 200', $code === 200, "Got HTTP {$code}");

$json = json_decode($raw, true);
dm_assert('meta-data is JSON',  $json !== null,         'Response is not valid JSON');
dm_assert('meta-data has ok',   array_key_exists('ok', $json ?? []), 'Missing ok field');

if (!empty($json['ok'])) {
    $data = $json['data'] ?? [];
    foreach (['spend','impressions','clicks','ctr'] as $field) {
        dm_assert("meta-data field: {$field}", array_key_exists($field, $data),
            "Missing required field '{$field}' in data");
    }
} else {
    // ok:false is acceptable if TikTok/Meta not connected for client 1
    dm_assert('meta-data error has message', !empty($json['error']) || !empty($json['message']),
        'ok:false but no error/message field');
}
