<?php

namespace App\Console\Commands;

use App\Models\SyncQueue;
use App\Support\DbRouter;
use App\Support\SyncManager;
use Illuminate\Console\Command;

class SyncDatabases extends Command
{
    protected $signature = 'tracker:sync
                            {--status : Only report what is pending, change nothing}';

    protected $description = 'Replay offline writes to Aiven and refresh the local mirror';

    public function handle(): int
    {
        $pending = SyncQueue::pending()->count();

        if ($this->option('status')) {
            $this->line('Primary : '.(DbRouter::ping() ? '<info>online</info>' : '<comment>offline</comment>'));
            $this->line('Pending : '.$pending);

            $failed = SyncQueue::pending()->where('attempts', '>', 0)->get();

            foreach ($failed as $entry) {
                $this->warn("  {$entry->action} {$entry->table_name}/{$entry->row_uuid} "
                    ."— {$entry->attempts} attempt(s): {$entry->last_error}");
            }

            return self::SUCCESS;
        }

        $this->info("Syncing… ({$pending} queued)");

        $result = SyncManager::run();

        if (! $result['ok']) {
            $this->error('Primary database is unreachable — nothing synced.');

            return self::FAILURE;
        }

        DbRouter::forget();

        $this->info("Pushed {$result['pushed']} queued change(s), refreshed {$result['pulled']} row(s).");

        $stuck = SyncQueue::pending()->count();

        if ($stuck > 0) {
            $this->warn("{$stuck} change(s) still pending — run with --status for details.");
        }

        return self::SUCCESS;
    }
}
