<?php

namespace App\Console\Commands;

use App\Enums\Status;
use App\Models\AdminRole;
use App\Models\AdminUser;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class CreateAdminCommand extends Command
{
    protected $signature = 'admin:create
                            {--username= : 管理员用户名}
                            {--email= : 管理员邮箱}
                            {--password= : 管理员密码}
                            {--name= : 管理员姓名}';

    protected $description = '创建或更新管理员账号，自动分配 super_admin 角色';

    public function handle(): int
    {
        $input = $this->gatherInput();

        if (!$this->validateInput($input)) {
            return self::FAILURE;
        }

        return DB::transaction(function () use ($input) {
            $adminUser = $this->createOrUpdateAdmin($input);
            $this->assignSuperAdminRole($adminUser);
            return self::SUCCESS;
        });
    }

    private function gatherInput(): array
    {
        return [
            'username' => $this->option('username') ?? $this->ask('请输入管理员用户名'),
            'password' => $this->option('password') ?? $this->secret('请输入管理员密码'),
            'name' => $this->option('name') ?? $this->ask('请输入管理员姓名', $this->option('username') ?? ''),
            'email' => $this->option('email') ?? $this->ask('请输入管理员邮箱', ''),
        ];
    }

    private function validateInput(array $input): bool
    {
        if (empty($input['username'])) {
            $this->error('用户名不能为空');
            return false;
        }

        if (empty($input['password'])) {
            $this->error('密码不能为空');
            return false;
        }

        if (strlen($input['password']) < 6) {
            $this->error('密码长度不能少于6位');
            return false;
        }

        if (!empty($input['email']) && !filter_var($input['email'], FILTER_VALIDATE_EMAIL)) {
            $this->error('邮箱格式不正确');
            return false;
        }

        return true;
    }

    private function createOrUpdateAdmin(array $input): AdminUser
    {
        $adminUser = AdminUser::where('username', $input['username'])->first();

        if ($adminUser) {
            $adminUser->update([
                'password' => Hash::make($input['password']),
                'name' => $input['name'],
                'email' => $input['email'],
            ]);
            $this->info("管理员账号 [{$input['username']}] 已更新");
        } else {
            $adminUser = AdminUser::create([
                'username' => $input['username'],
                'password' => Hash::make($input['password']),
                'name' => $input['name'],
                'email' => $input['email'],
                'status' => Status::ENABLED,
            ]);
            $this->info("管理员账号 [{$input['username']}] 创建成功");
        }

        return $adminUser;
    }

    private function assignSuperAdminRole(AdminUser $adminUser): void
    {
        $superAdminRole = AdminRole::where('code', 'super_admin')->first();

        if (!$superAdminRole) {
            $this->warn('未找到 super_admin 角色，请先创建该角色');
            return;
        }

        if ($adminUser->roles()->where('admin_roles.id', $superAdminRole->id)->exists()) {
            $this->info('super_admin 角色已存在，跳过分配');
            return;
        }

        $adminUser->roles()->attach($superAdminRole->id);
        $this->info('已分配 super_admin 角色');
    }
}
