<?php
// Backfill transactions table from deals.payments JSON (only when no transactions exist for the deal).

require __DIR__ . '/../../vendor/autoload.php';
$app = require __DIR__ . '/../../app/bootstrap.php';

$pdo = $app->db->getPdo();

$force = in_array('--force', $argv ?? [], true);

$sql = "
    SELECT d.id, d.didar_deal_id, d.payments
    FROM deals d
    WHERE d.payments IS NOT NULL
      AND d.payments <> ''
      AND d.payments <> '[]'
      " . ($force ? "" : "AND NOT EXISTS (SELECT 1 FROM transactions t WHERE t.deal_id = d.id)") . "
";

$stmt = $pdo->query($sql);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

$updated = 0;
$skipped = 0;
$errors = 0;

foreach ($rows as $row) {
    $dealKey = $row['didar_deal_id'] ?: (string)$row['id'];
    $paymentsRaw = $row['payments'] ?? '';
    $payments = json_decode($paymentsRaw, true);
    if (!is_array($payments) || empty($payments)) {
        $skipped++;
        continue;
    }

    try {
        if ($force) {
            $pdo->prepare("DELETE FROM transactions WHERE deal_id = ?")->execute([$row['id']]);
        }
        $app->services->deal->syncTransactionsFromPayments($dealKey, $payments);
        $updated++;
    } catch (\Throwable $e) {
        $errors++;
        echo "Failed deal {$dealKey}: " . $e->getMessage() . PHP_EOL;
    }
}

echo "Backfill complete. Total: " . count($rows) . ", Updated: {$updated}, Skipped: {$skipped}, Errors: {$errors}" . PHP_EOL;
