<?php
declare(strict_types=1);

use App\Core\App;
use App\Core\Database;
use App\Modules\Accounting\Services\GLSyncService;

/**
 * Sync ALL existing financial data into the General Ledger.
 *
 * Delegates to GLSyncService which is also callable from the web UI
 * (Accounting Dashboard → "مزامنة GL" button).
 *
 * SAFE TO RE-RUN: Idempotent — skips records that already have journal entries.
 *
 * PREREQUISITE: Phase_36_002_seed_fiscal_year should run first (but GLSyncService
 * also creates fiscal years internally, so it's self-healing).
 *
 * Run: php cli.php seed
 */
return function (Database $db): void {

    // AccountingIntegrationService and JournalService use App::getInstance()->db()
    // internally. In CLI context, App is not booted, so we inject the db instance.
    App::getInstance()->setDb($db);

    echo "  Running GL sync...\n";

    $result = GLSyncService::syncAll();

    $total = $result['payments'] + $result['fines'] + $result['installments']
           + $result['sales'] + $result['payroll'] + $result['refunds'] + $result['rentals'];

    echo "    Payments:     {$result['payments']}\n";
    echo "    Fines:        {$result['fines']}\n";
    echo "    Installments: {$result['installments']}\n";
    echo "    Sales COGS:   {$result['sales']}\n";
    echo "    Payroll:      {$result['payroll']}\n";
    echo "    Refunds:      {$result['refunds']}\n";
    echo "    Rentals:      {$result['rentals']}\n";
    echo "    ──────────────────\n";
    echo "    Total synced:  {$total}\n";
    echo "    Errors:        {$result['errors']}\n";

    if ($result['errors'] > 0) {
        echo "\n  WARNING: Some entries failed. Check logs for details.\n";
    }
};
