<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

final class LotteryDatabaseInitCommand extends Command
{
    protected $signature = 'lottery:db-init
        {--fresh : 先执行 migrate:fresh，再初始化数据库}
        {--demo : 额外写入演示数据（生产环境默认关闭）}
        {--no-demo : 禁止写入演示数据}
        {--skip-auth-sync : 跳过后台权限注册表同步}';

    protected $description = '统一初始化数据库：纯迁移链、基础种子、后台权限同步，以及非生产演示数据';

    public function handle(): int
    {
        $isProduction = app()->environment('production');
        $seedDemo = $this->shouldSeedDemo($isProduction);
        $migrationCommand = (bool) $this->option('fresh') ? 'migrate:fresh' : 'migrate';

        $this->components->info(sprintf(
            '开始数据库初始化：%s%s',
            $migrationCommand,
            $seedDemo ? ' + foundation seed + demo seed' : ' + foundation seed',
        ));

        $migrateExit = $this->call($migrationCommand, [
            '--force' => true,
        ]);
        if ($migrateExit !== self::SUCCESS) {
            return $migrateExit;
        }

        $foundationExit = $this->call('db:seed', [
            '--class' => 'Database\\Seeders\\FoundationSeeder',
            '--force' => true,
        ]);
        if ($foundationExit !== self::SUCCESS) {
            return $foundationExit;
        }

        if (! (bool) $this->option('skip-auth-sync')) {
            $authExit = $this->call('lottery:admin-auth-sync', [
                '--audit' => true,
            ]);
            if ($authExit !== self::SUCCESS) {
                return $authExit;
            }
        }

        if ($seedDemo) {
            if ($isProduction) {
                $this->components->error('production 环境禁止写入演示数据。');

                return self::FAILURE;
            }

            $demoExit = $this->call('db:seed', [
                '--class' => 'Database\\Seeders\\LocalDemoSeeder',
                '--force' => true,
            ]);
            if ($demoExit !== self::SUCCESS) {
                return $demoExit;
            }
        }

        $this->newLine();
        $this->components->info('数据库初始化完成。');
        $this->line(sprintf('环境：%s', app()->environment()));
        $this->line(sprintf('演示数据：%s', $seedDemo ? '已写入' : '未写入'));
        $this->line('统一入口命令：php artisan lottery:db-init');

        return self::SUCCESS;
    }

    private function shouldSeedDemo(bool $isProduction): bool
    {
        if ((bool) $this->option('no-demo')) {
            return false;
        }

        if ((bool) $this->option('demo')) {
            return true;
        }

        return ! $isProduction;
    }
}
