<?php

namespace App\Commands;

use App\Libraries\GiteaSyncService;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;

class SyncGiteaData extends BaseCommand
{
	protected $group = 'Gitea';
	protected $name = 'gitea:sync';
	protected $description = 'Full sync all users, repositories, commits, and pull requests from Gitea into local database.';

	public function run(array $params)
	{
		CLI::write('Starting Gitea full sync...', 'yellow');

		$service = new GiteaSyncService();
		$result = $service->syncFull();

		if (!($result['success'] ?? false)) {
			CLI::error('Sync failed: ' . ($result['message'] ?? 'Unknown error'));
			return;
		}

		$stats = $result['stats'] ?? [];
		CLI::write('Sync done.', 'green');
		CLI::write('Users: ' . ($stats['users_synced'] ?? 0));
		CLI::write('Repositories: ' . ($stats['repositories_synced'] ?? 0));
		CLI::write('Commits: ' . ($stats['commits_synced'] ?? 0));
		CLI::write('Pull Requests: ' . ($stats['pull_requests_synced'] ?? 0));

		$errors = $stats['errors'] ?? [];
		if (!empty($errors)) {
			CLI::newLine();
			CLI::write('Warnings / Errors:', 'yellow');
			foreach ($errors as $error) {
				CLI::write('- ' . $error, 'light_red');
			}
		}
	}
}
