<?php

namespace Kylin\Licensing\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Kylin\Licensing\Services\LicenseVerifier;

/**
 * 许可证状态命令
 */
class LicenseStatusCommand extends Command
{
    protected $signature = 'kylin:license-status';

    protected $description = '查看 Kylin 许可证状态';

    public function handle(LicenseVerifier $verifier): int
    {
        $data = $verifier->getLicenseData();

        if ($data === null) {
            $this->components->error('未安装许可证');
            $this->newLine();
            $this->components->info('请执行 php artisan kylin:license-activate <KEY> 激活许可证');
            return self::FAILURE;
        }

        $status = $data['status'] ?? 0;
        $expiresAt = $data['expires_at'] ?? null;
        $isValid = $status === 1 && ($expiresAt === null || ! \Carbon\Carbon::parse($expiresAt)->isPast());

        $statusBadge = $isValid ? '<fg=green>有效</>' : '<fg=red>无效</>';
        $error = $verifier->getError();
        $graceBadge = ($error && ($error['code'] ?? '') === 'LCS-GRACE-001') ? ' <fg=yellow>(宽限期)</>' : '';

        $this->line('');
        $this->line('<fg=cyan;bold>  Kylin 许可证状态</>');
        $this->line('<fg=cyan;bold>  ═══════════════════════════════════════</>');
        $this->components->twoColumnDetail('状态', $statusBadge . $graceBadge);
        $this->components->twoColumnDetail('许可证密钥', $data['license_key'] ?? '-');
        $this->components->twoColumnDetail('类型', $data['type'] ?? '-');
        $this->components->twoColumnDetail('客户', $data['customer_name'] ?? '-');
        $this->components->twoColumnDetail('绑定域名', $data['domain'] ?? '不限');
        $this->components->twoColumnDetail('授权包', implode(', ', $data['packages'] ?? ['全部']));
        $this->components->twoColumnDetail('最大设备数', (string) ($data['max_devices'] ?? 1));
        $this->components->twoColumnDetail('签发时间', $data['issued_at'] ?? '-');
        $this->components->twoColumnDetail('过期时间', $expiresAt ?? '永久');

        if ($expiresAt !== null) {
            $remaining = (int) now()->diffInDays(\Carbon\Carbon::parse($expiresAt), false);
            $this->components->twoColumnDetail('剩余天数', $remaining > 0 ? (string) $remaining : '<fg=red>已过期</>');
        }

        $this->line('');
        return self::SUCCESS;
    }
}
