<?php

declare(strict_types=1);

namespace App\Command;

use App\Model\User;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Psr\Container\ContainerInterface;

#[Command]
class AppInstall extends HyperfCommand
{
    public function __construct(protected ContainerInterface $container)
    {
        parent::__construct('app:install');
    }

    public function configure()
    {
        parent::configure();
        $this->setDescription('Install application and create default admin user');
    }

    public function handle()
    {
        $this->line('Starting application installation...', 'info');

        // 检查 admin 用户是否已存在
        $existingUser = User::query()
            ->where('username', 'adminstrator')
            ->orWhere('email', 'admin@admin.com')
            ->first();

        if ($existingUser) {
            $this->error('Admin user already exists!');
            $this->line('Username: ' . $existingUser->username);
            $this->line('Email: ' . $existingUser->email);
            return 1;
        }

        // 创建默认 admin 用户
        try {
            $user = User::create([
                'username' => 'adminstrator',
                'email' => 'admin@admin.com',
                'password' => 'admin',
                'status' => 1,
                'ext' => [],
            ]);

            $this->line('Default admin user created successfully!', 'info');
            $this->line('Username: adminstrator', 'comment');
            $this->line('Email: admin@admin.com', 'comment');
            $this->line('Password: admin', 'comment');
            $this->line('');
            $this->warn('Please change the default password after first login!');

            return 0;
        } catch (\Exception $e) {
            $this->error('Failed to create admin user: ' . $e->getMessage());
            return 1;
        }
    }
}
