<?php

require_once __DIR__ . '/agent_service.php';

function ua_agent_migrate_legacy(mysqli $conn): array {
  ua_agent_schema_migrate($conn);
  $summary = ['transactions'=>0,'opening_entries'=>0,'agents_checked'=>0,'errors'=>[]];
  $legacyBalances = [];
  $balanceRs = @$conn->query("SELECT id,balance FROM agents WHERE archived_at IS NULL ORDER BY id");
  if ($balanceRs) while ($agent = $balanceRs->fetch_assoc()) {
    $legacyBalances[(int)$agent['id']] = round((float)$agent['balance'], 2);
  }

  if (ua_agent_schema_table_exists($conn, 'agent_transactions')) {
    $rs = @$conn->query("SELECT * FROM agent_transactions ORDER BY id ASC");
    if ($rs) while ($row = $rs->fetch_assoc()) {
      $amount = (float)($row['amount'] ?? 0);
      if ($amount == 0.0) continue;
      $result = ua_agent_ledger_post($conn, [
        'agent_id'=>(int)$row['agent_id'],
        'direction'=>$amount >= 0 ? 'DEBIT' : 'CREDIT',
        'entry_type'=>'LEGACY_' . strtoupper(substr((string)($row['type'] ?? 'TRANSACTION'), 0, 40)),
        'amount'=>abs($amount),
        'source_type'=>'agent_transactions',
        'source_id'=>(string)$row['id'],
        'idempotency_key'=>'LEGACY_AGENT_TX:' . (int)$row['id'],
        'description'=>(string)($row['note'] ?? ''),
        'occurred_at'=>(string)($row['created_at'] ?? date('Y-m-d H:i:s')),
        'created_by_type'=>'migration',
      ]);
      if ($result['ok'] && empty($result['duplicate'])) $summary['transactions']++;
      if (!$result['ok']) $summary['errors'][] = 'Transaction ' . (int)$row['id'] . ': ' . $result['error'];
    }
  }

  foreach ($legacyBalances as $agentId => $legacyBalance) {
    $summary['agents_checked']++;
    $ledgerBalance = ua_agent_ledger_balance($conn, $agentId);
    $difference = round($legacyBalance - $ledgerBalance, 2);
    if (abs($difference) < 0.005) continue;
    $result = ua_agent_ledger_post($conn, [
      'agent_id'=>$agentId,
      'direction'=>$difference > 0 ? 'DEBIT' : 'CREDIT',
      'entry_type'=>'OPENING_BALANCE',
      'amount'=>abs($difference),
      'source_type'=>'legacy_balance',
      'source_id'=>(string)$agentId,
      'idempotency_key'=>'LEGACY_OPENING_BALANCE:' . $agentId,
      'description'=>'قيد افتتاحي لمطابقة الرصيد السابق عند الترحيل.',
      'metadata'=>['legacy_balance'=>$legacyBalance,'ledger_before'=>$ledgerBalance],
      'created_by_type'=>'migration',
    ]);
    if ($result['ok'] && empty($result['duplicate'])) $summary['opening_entries']++;
    if (!$result['ok']) $summary['errors'][] = 'Agent ' . $agentId . ': ' . $result['error'];
  }

  return ['ok'=>empty($summary['errors'])] + $summary;
}
