<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Models\User;
use App\Services\DberpAdminAccessService;
use Illuminate\Console\Command;
use Illuminate\Support\Env;
use Illuminate\Support\Facades\Schema;
use Throwable;

final class DberpPanelInstallCommand extends Command
{
    protected $signature = 'dberp:panel-install';

    protected $description = 'DBPanel 极速安装：从环境变量创建首任超级管理员';

    public function handle(DberpAdminAccessService $adminAccessService): int
    {
        $adminName = $this->readRequiredEnv('DBERP_PANEL_ADMIN_NAME', '管理员姓名');
        if ($adminName === null) {
            return self::FAILURE;
        }

        $loginAccount = $this->readRequiredEnv('DBERP_PANEL_LOGIN_ACCOUNT', '登录账号');
        if ($loginAccount === null) {
            return self::FAILURE;
        }

        $password = $this->readRequiredEnv('DBERP_PANEL_ADMIN_PASSWORD', '管理员密码');
        if ($password === null) {
            return self::FAILURE;
        }

        $email = $this->readOptionalEnv('DBERP_PANEL_ADMIN_EMAIL');
        if ($email !== null && filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
            $this->error('DBERP_PANEL_ADMIN_EMAIL 格式无效。');

            return self::FAILURE;
        }

        if (! Schema::hasTable('users')) {
            $this->error('users 数据表不存在，请先完成数据库迁移后再创建管理员。');

            return self::FAILURE;
        }

        $loginAccount = trim($loginAccount);

        if (User::query()->where('login_account', $loginAccount)->exists()) {
            $this->line('panel_install_admin_exists');

            return self::SUCCESS;
        }

        try {
            $adminAccessService->bootstrapInstallationSuperAdministrator([
                'name' => $adminName,
                'login_account' => $loginAccount,
                'email' => $email,
                'password' => $password,
                'nickname' => $adminName,
            ]);
        } catch (Throwable $e) {
            $this->error('创建超级管理员失败：'.$e->getMessage());

            return self::FAILURE;
        }

        $this->line('panel_install_admin_ok');

        return self::SUCCESS;
    }

    private function readRequiredEnv(string $key, string $label): ?string
    {
        $value = $this->readEnv($key);

        if ($value === null) {
            $this->error("缺少环境变量 {$key}（{$label}）。");

            return null;
        }

        return $value;
    }

    private function readOptionalEnv(string $key): ?string
    {
        return $this->readEnv($key);
    }

    private function readEnv(string $key): ?string
    {
        $raw = Env::get($key);

        if (! is_string($raw)) {
            return null;
        }

        $trimmed = trim($raw);

        return $trimmed === '' ? null : $trimmed;
    }
}
