<?php
/**
 * Strategy change history — GET /api/strategy/changes?strategy_id=X
 * TRADERALIGN STRATEGY BUSINESS RULES redesign (2026-08-11).
 *
 * Returns the real, recorded strategy_change_events/strategy_change_fields
 * for one strategy (ownership-checked), plus a data-driven narration
 * (StrategyChangeHistory::narrate() — never a hardcoded sentence). Used by
 * Strategy Builder's own "View Change History" panel, and can be reused
 * anywhere else in the app that needs the same real history (Reports'
 * period view, Journal's single-trade Four-Stage view).
 */
header('Content-Type: application/json');

require_once __DIR__ . '/../../src/StrategyChangeHistory.php';

try {
    $userId = $auth->requireAuth();

    $strategyId = $_GET['strategy_id'] ?? null;
    if (!$strategyId) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing strategy_id']);
        exit;
    }

    $strategy = $db->selectById('strategies', $strategyId);
    if (!$strategy) {
        http_response_code(404);
        echo json_encode(['error' => 'Strategy not found']);
        exit;
    }
    if ($strategy['user_id'] !== $userId) {
        http_response_code(403);
        echo json_encode(['error' => 'Access denied']);
        exit;
    }

    $events = StrategyChangeHistory::fetchEvents($db, $strategyId);

    $formatted = array_map(function ($e) {
        return [
            'id' => $e['id'],
            'changed_at' => $e['changed_at'],
            'fields' => array_map(function ($f) {
                return [
                    'field' => $f['field_name'],
                    'label' => StrategyChangeHistory::fieldLabel($f['field_name']),
                    'previous' => $f['previous_value'],
                    'new' => $f['new_value'],
                ];
            }, $e['fields']),
        ];
    }, $events);

    echo json_encode([
        'strategy_id' => $strategyId,
        'strategy_name' => $strategy['name'],
        'total_changes' => count($events),
        'narration' => StrategyChangeHistory::narrate($events),
        'events' => array_reverse($formatted), // newest first for display
    ]);
} catch (\Throwable $e) {
    error_log('Strategy changes error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Server error']);
}
