<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;

final class QuickQuizInstall extends Command
{
    protected $signature = 'quickquiz:install
        {--admin-email=admin@example.com : 首个管理员邮箱}
        {--admin-password=123456 : 首个管理员密码}
        {--fresh : 使用 migrate:fresh 重建数据库}';

    protected $description = 'Install QuickQuiz by running migrations, seeders, and creating the first administrator.';

    public function handle(): int
    {
        if (! config('app.key')) {
            Artisan::call('key:generate', ['--force' => true]);
        }

        if (! config('jwt.secret')) {
            Artisan::call('jwt:secret', ['--force' => true]);
        }

        Artisan::call($this->option('fresh') ? 'migrate:fresh' : 'migrate', ['--force' => true]);
        $this->output->write(Artisan::output());

        Artisan::call('db:seed', ['--force' => true]);
        $this->output->write(Artisan::output());

        User::query()->updateOrCreate([
            'email' => (string) $this->option('admin-email'),
        ], [
            'name' => '系统管理员',
            'role' => 'admin',
            'is_active' => true,
            'password' => Hash::make((string) $this->option('admin-password')),
        ]);

        Storage::put('installed.lock', now()->toIso8601String());
        $this->info('QuickQuiz installed.');

        return self::SUCCESS;
    }
}
