<?php

namespace App\Console\Commands;

use App\Core\Services\Update\UpdateChecker;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class CheckForUpdates extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'updates:check {--force : Force check even if recently checked}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Check for available system updates';

    /**
     * Execute the console command.
     */
    public function handle(UpdateChecker $updateChecker): int
    {
        $this->info('Checking for updates...');

        try {
            $force = $this->option('force');
            $result = $updateChecker->checkForUpdates($force);

            if ($result['success']) {
                if ($result['has_update'] ?? false) {
                    $this->info("Update available! Latest version: {$result['latest_version']}");
                    $this->info("Current version: {$result['current_version']}");
                    Log::info('Update check completed: Update available', $result);

                    return Command::SUCCESS;
                } else {
                    $this->info("You are running the latest version ({$result['current_version']}).");
                    Log::info('Update check completed: Up to date', $result);

                    return Command::SUCCESS;
                }
            } else {
                $this->error('Update check failed: '.($result['message'] ?? 'Unknown error'));
                Log::warning('Update check failed', $result);

                return Command::FAILURE;
            }
        } catch (\Exception $e) {
            $this->error('Error checking for updates: '.$e->getMessage());
            Log::error('Update check error', ['error' => $e->getMessage()]);

            return Command::FAILURE;
        }
    }
}
