<?php

namespace App\Console\Commands;

use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;

use function Laravel\Prompts\confirm;
use function Laravel\Prompts\password;
use function Laravel\Prompts\text;

class InstallCommand extends Command
{
    protected $signature = 'medibook:install {--force : Run without confirmation}';

    protected $description = 'Check the environment, migrate, seed, and create the super admin.';

    public function handle(): int
    {
        $this->components->info('MediBook AI installer');

        // 1. Environment checks
        $checks = [
            'PHP >= 8.3' => version_compare(PHP_VERSION, '8.3.0', '>='),
            'ext-pdo_mysql' => extension_loaded('pdo_mysql'),
            'ext-gd or ext-imagick' => extension_loaded('gd') || extension_loaded('imagick'),
            'ext-intl' => extension_loaded('intl'),
            'ext-mbstring' => extension_loaded('mbstring'),
            'APP_KEY set' => filled(config('app.key')),
            'storage/ writable' => is_writable(storage_path()),
        ];

        $failed = false;
        foreach ($checks as $label => $ok) {
            $ok
                ? $this->components->twoColumnDetail($label, '<fg=green>OK</>')
                : $this->components->twoColumnDetail($label, '<fg=red>FAILED</>');
            $failed = $failed || ! $ok;
        }

        try {
            DB::connection()->getPdo();
            $this->components->twoColumnDetail('Database connection', '<fg=green>OK</>');
        } catch (\Throwable $e) {
            $this->components->twoColumnDetail('Database connection', '<fg=red>FAILED</>');
            $this->components->error($e->getMessage());
            $failed = true;
        }

        if ($failed) {
            $this->components->error('Fix the failed checks above, then run the installer again.');

            return self::FAILURE;
        }

        if (! $this->option('force') && ! confirm('Run migrations and seeders now?', true)) {
            return self::SUCCESS;
        }

        // 2. Migrate + seed
        Artisan::call('migrate', ['--force' => true], $this->output);
        Artisan::call('db:seed', ['--force' => true], $this->output);

        // 3. Super admin
        if (User::withoutGlobalScope('tenant')->whereNull('tenant_id')->doesntExist()) {
            $this->components->info('Create the super admin account');
            $name = text('Name', default: 'Super Admin');
            $email = text('Email', validate: fn ($v) => filter_var($v, FILTER_VALIDATE_EMAIL) ? null : 'Invalid email.');
            $pass = password('Password (min 8 chars)', validate: fn ($v) => strlen($v) >= 8 ? null : 'Too short.');

            $admin = User::withoutEvents(fn () => User::create([
                'name' => $name,
                'email' => strtolower($email),
                'password' => $pass,
                'email_verified_at' => now(),
            ]));
            $admin->assignRole('super_admin');

            $this->components->info('Super admin created. Log in at https://'.config('tenancy.central_domain').'/login');
        } else {
            $this->components->warn('A super admin already exists — skipping.');
        }

        $this->components->info('Done. Add the cron entry: * * * * * php artisan schedule:run');

        return self::SUCCESS;
    }
}
