<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Domain\Account\Models\Account;
use App\Domain\Package\Models\Package;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class CreateAccountCommand extends Command
{
    protected $signature = 'onox:create-account
                            {--username= : Linux username (onx_xxxxx)}
                            {--email= : Customer email}
                            {--password= : Customer password (auto-generate if omitted)}
                            {--package= : Package slug (default: medium)}
                            {--domain= : Primary domain}
                            {--name= : Customer full name}';

    protected $description = 'Yeni hosting hesabı oluştur (CLI provisioning — admin yokken kullanışlı)';

    public function handle(): int
    {
        $email = $this->option('email') ?: $this->ask('Customer e-postası');
        if (! filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $this->error("Geçersiz e-posta: {$email}");

            return self::FAILURE;
        }

        if (User::where('email', $email)->exists()) {
            $this->error("Bu e-posta zaten kayıtlı: {$email}");

            return self::FAILURE;
        }

        $username = $this->option('username') ?: $this->ask('Linux username (onx_xxxxx)', 'onx_'.Str::random(6));
        if (Account::where('username', $username)->exists()) {
            $this->error("Bu username zaten kullanılıyor: {$username}");

            return self::FAILURE;
        }

        $name = $this->option('name') ?: $this->ask('İsim', explode('@', $email)[0]);
        $password = $this->option('password') ?: Str::password(16);
        $domain = $this->option('domain');
        $packageSlug = $this->option('package') ?: 'medium';

        $package = Package::where('slug', $packageSlug)->first();
        if (! $package) {
            $this->error("Paket bulunamadı: {$packageSlug}");
            $this->line('Mevcut paketler: '.Package::pluck('slug')->join(', '));

            return self::FAILURE;
        }

        // Confirm
        $this->newLine();
        $this->line('═══════════════════════════════════════');
        $this->line("  Email:    <fg=cyan>{$email}</>");
        $this->line("  Name:     {$name}");
        $this->line("  Username: <fg=cyan>{$username}</>");
        $this->line('  Domain:   '.($domain ?: '<none>'));
        $this->line("  Package:  {$package->name} ({$package->slug})");
        $this->line('═══════════════════════════════════════');

        if (! $this->option('no-interaction') && ! $this->confirm('Devam edilsin mi?', true)) {
            $this->warn('İptal edildi.');

            return self::FAILURE;
        }

        // Create user
        $user = User::create([
            'name' => $name,
            'email' => $email,
            'password' => Hash::make($password),
            'email_verified_at' => now(),
        ]);
        $user->assignRole('user');

        // Create account
        $quota = $package->limit('disk_mb') ? $package->limit('disk_mb') * 1024 * 1024 : null;

        $account = Account::create([
            'owner_user_id' => $user->id,
            'package_id' => $package->id,
            'username' => $username,
            'email' => $email,
            'primary_domain' => $domain,
            'status' => 'pending',
            'quota_bytes' => $quota,
            'disk_usage_bytes' => 0,
        ]);

        $this->newLine();
        $this->info('✓ Hesap başarıyla oluşturuldu!');
        $this->newLine();
        $this->line("  Account ID: <fg=cyan>{$account->id}</>");
        $this->line("  User ID:    {$user->id}");
        $this->line("  Login:      {$email}");
        $this->line("  Password:   <fg=yellow>{$password}</>");
        $this->line('              (Bu parolayı şimdi kaydet — geri gösterilmez!)');
        $this->newLine();
        $this->warn('Hesap durumu "pending" — admin paneli veya `onox:provision {$account->id}` ile aktifleştir.');
        $this->newLine();

        return self::SUCCESS;
    }
}
