<?php

declare(strict_types=1);

namespace App\Command;

use App\Model\Role; // phpcs:ignore -- used in handle()
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', 'administrator')
            ->orWhere('email', 'admin@admin.com')
            ->first();

        if ($existingUser) {
            $this->line('Admin user already exists.', 'comment');
            $this->line('Username: ' . $existingUser->username);
            $this->line('Email: ' . $existingUser->email);

            // 自动修复：缺失的 role_id
            $adminRole = Role::query()->where('name', 'administrator')->first();
            if ($adminRole && $existingUser->role_id !== $adminRole->id) {
                $existingUser->role_id = $adminRole->id;
                $existingUser->save();
                $this->line('Fixed: role_id set to administrator.', 'info');
            }

            // 自动修复：旧拼写错误的用户名
            if ($existingUser->username === 'adminstrator') {
                $existingUser->username = 'administrator';
                $existingUser->save();
                $this->line('Fixed: username corrected to "administrator".', 'info');
            }

            $this->call('route:sync');
            $this->call('route-group:seed');

            return 0;
        }

        // 创建默认 admin 用户
        try {
            $adminRole = Role::query()->where('name', 'administrator')->first();
            if (!$adminRole) {
                $this->error('Role "administrator" not found. Please run migrations first.');
                return 1;
            }

            $user = User::create([
                'username' => 'administrator',
                'email' => 'admin@admin.com',
                'password' => 'admin',
                'status' => 1,
                'role_id' => $adminRole->id,
                'ext' => [],
            ]);

            $this->line('Default admin user created successfully!', 'info');
            $this->line('Username: administrator', '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!');

            $this->call('route:sync');
            $this->call('route-group:seed');

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