<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Domain\Account\Models\Account;
use Illuminate\Console\Command;

class AccountListCommand extends Command
{
    protected $signature = 'onox:accounts
                            {--status= : Filter by status (active|suspended|pending|terminated)}
                            {--limit=50}
                            {--json}';

    protected $description = 'Tüm hesapları listele';

    public function handle(): int
    {
        $query = Account::with(['package', 'owner']);
        if ($status = $this->option('status')) {
            $query->where('status', $status);
        }
        $accounts = $query->latest()->take((int) $this->option('limit'))->get();

        if ($this->option('json')) {
            $this->line($accounts->toJson(JSON_PRETTY_PRINT));

            return self::SUCCESS;
        }

        if ($accounts->isEmpty()) {
            $this->warn('Hesap bulunamadı.');

            return self::SUCCESS;
        }

        $this->table(
            ['ID', 'Username', 'Email', 'Domain', 'Package', 'Status', 'Owner'],
            $accounts->map(fn ($a) => [
                $a->id,
                $a->username,
                $a->email,
                $a->primary_domain ?: '—',
                $a->package?->name ?? '—',
                $a->status->value,
                $a->owner?->email ?? '—',
            ])->toArray(),
        );

        $this->info("Toplam: {$accounts->count()} hesap gösterildi.");

        return self::SUCCESS;
    }
}
