<?php
// tests/test-meta-placement.php — Verify meta-data.php breakdown/placement endpoint
require_once __DIR__ . '/run.php';

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

// ── 1. Auth block (no session) ────────────────────────────────────────────────
$url = "{$base}/api/meta-data.php?action=breakdown&client_id=1&period=30d&breakdown=publisher_platform";
$ch  = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => false,
    CURLOPT_TIMEOUT        => 15,
]);
$raw  = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$json    = json_decode($raw, true);
$blocked = ($code === 401 || $code === 302 || $code === 403)
        || ($json && isset($json['ok']) && $json['ok'] === false);
dm_assert('meta-placement: auth block (no session)', $blocked,
    "Expected 401/302/403 or ok:false, got HTTP {$code}");

// ── 2. Response structure (with session) ──────────────────────────────────────
if (!$session) {
    dm_skip('meta-placement: response shape',   'TEST_SESSION_COOKIE not set');
    dm_skip('meta-placement: breakdown is array','TEST_SESSION_COOKIE not set');
    return;
}

$ch2 = curl_init($url);
curl_setopt_array($ch2, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 20,
    CURLOPT_HTTPHEADER     => ["Cookie: {$session}"],
]);
$raw2  = curl_exec($ch2);
$code2 = curl_getinfo($ch2, CURLINFO_HTTP_CODE);
curl_close($ch2);

dm_assert('meta-placement: HTTP 200', $code2 === 200, "Got HTTP {$code2}");

$json2 = json_decode($raw2, true);
dm_assert('meta-placement: is valid JSON', $json2 !== null, 'Response is not valid JSON');
dm_assert('meta-placement: has ok field',  array_key_exists('ok', $json2 ?? []), 'Missing ok field');

if (!empty($json2['ok'])) {
    // Successful response: breakdown must be a non-empty array
    dm_assert('meta-placement: breakdown is array',
        isset($json2['breakdown']) && is_array($json2['breakdown']),
        'Missing breakdown array in ok:true response');

    if (!empty($json2['breakdown'])) {
        $first = $json2['breakdown'][0];
        foreach (['label', 'spend', 'impressions'] as $field) {
            dm_assert("meta-placement: breakdown[0] has {$field}",
                array_key_exists($field, $first),
                "Missing field '{$field}' in first breakdown row");
        }
        dm_assert('meta-placement: spend is numeric',
            is_numeric($first['spend'] ?? null),
            'spend field should be numeric');
    } else {
        dm_skip('meta-placement: breakdown row fields', 'breakdown is empty — Meta not connected or no spend');
    }
} else {
    // ok:false is acceptable when Meta Ads not connected for client 1
    dm_assert('meta-placement: error has message',
        !empty($json2['error']) || !empty($json2['message']),
        'ok:false but no error/message field');
    dm_skip('meta-placement: breakdown row fields', 'ok:false — Meta probably not connected for client 1');
}
