<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Services\ServerHunterService;
use Illuminate\Console\Command;

class SyncServerHunterCommand extends Command
{
    protected $signature = 'serverhunter:sync {--dry-run : Preview the feed without pushing to ServerHunter}';

    protected $description = 'Push VPS and dedicated server offers to the ServerHunter API';

    public function __construct(
        private ServerHunterService $serverHunterService,
    ) {
        parent::__construct();
    }

    public function handle(): int
    {
        $feed = $this->serverHunterService->buildFeed();
        $offerCount = count($feed['offers']);

        if ($offerCount === 0) {
            $this->warn('No active VPS or dedicated plans found. Nothing to sync.');

            return self::SUCCESS;
        }

        $this->info("Found {$offerCount} offer(s) to sync with ServerHunter.");

        if ($this->option('dry-run')) {
            $this->info('Dry run — not pushing to API. Feed preview:');
            $this->newLine();

            foreach ($feed['offers'] as $offer) {
                $this->line(sprintf(
                    '  [%s] %s — $%s/mo (%s, %s cores, %sMB RAM, %sGB %s)',
                    $offer['product_type'],
                    $offer['name'],
                    $offer['price'],
                    $offer['cpu_name'],
                    $offer['cpu_cores'],
                    $offer['memory_amount'],
                    $offer['ssd_capacity'] > 0 ? $offer['ssd_capacity'] : $offer['hdd_capacity'],
                    $offer['ssd_capacity'] > 0 ? 'SSD/NVMe' : 'HDD',
                ));
            }

            $this->newLine();
            $this->info('Full JSON output:');
            $this->line(json_encode($feed, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));

            return self::SUCCESS;
        }

        $this->info('Pushing offers to ServerHunter API...');

        try {
            $result = $this->serverHunterService->pushToApi($feed);

            if ($result['successful']) {
                $this->info("Successfully pushed {$offerCount} offer(s) to ServerHunter.");

                return self::SUCCESS;
            }

            $this->error("ServerHunter API returned HTTP {$result['status']}.");
            $this->line(json_encode($result['body'], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));

            return self::FAILURE;
        } catch (\RuntimeException $e) {
            $this->error($e->getMessage());

            return self::FAILURE;
        }
    }
}
