<?php

namespace Maestro\Core\Console\Commands;

use Illuminate\Console\Command;

class InstallCommand extends Command
{
    protected $signature   = 'maestro:install';
    protected $description = 'Install Maestro into this project';

    public function handle(): void
    {
        $this->newLine();
        $this->line('  <fg=cyan;options=bold>Maestro Installer</>');
        $this->line('  ' . str_repeat('─', 40));
        $this->newLine();

        $this->line('  <fg=yellow>→</> Publishing config');
        $this->callSilent('vendor:publish', [
            '--tag'   => 'maestro-config',
            '--force' => false,
        ]);

        $this->line('  <fg=yellow>→</> Publishing frontend stubs');
        $this->callSilent('vendor:publish', [
            '--tag'   => 'maestro-frontend',
            '--force' => true,
        ]);

        $this->line('  <fg=yellow>→</> Publishing Spatie permission migrations');
        $this->callSilent('vendor:publish', [
            '--provider' => 'Spatie\\Permission\\PermissionServiceProvider',
            '--force'    => false,
        ]);

        $this->line('  <fg=yellow>→</> Publishing Reverb config');
        $this->callSilent('vendor:publish', [
            '--tag'   => 'reverb-config',
            '--force' => false,
        ]);

        $this->line('  <fg=yellow>→</> Running migrations');
        $this->call('migrate', ['--quiet' => true]);

        $this->line('  <fg=yellow>→</> Seeding base data');
        $this->call('db:seed', [
            '--class' => 'Maestro\\Core\\Database\\Seeders\\MaestroSeeder',
            '--quiet' => true,
        ]);

        $this->line('  <fg=yellow>→</> Configuring .env');
        $this->configureEnv();

        $this->newLine();
        $this->line('  <fg=green;options=bold>✓ Maestro installed successfully.</>');
        $this->newLine();
        $this->line('  <options=bold>Login credentials:</>');
        $this->line('  Email:    <fg=yellow>admin@example.com</>');
        $this->line('  Password: <fg=yellow>password</>');
        $this->newLine();
        $this->line('  <options=bold>Next steps:</>');
        $this->line('  1. Run <fg=yellow>npm install</>');
        $this->line('  2. Run <fg=yellow>npm run dev</>');
        $this->line('  3. Update <fg=yellow>REVERB_*</> in <fg=yellow>.env</> for production');
        $this->newLine();
    }

    protected function configureEnv(): void
    {
        $envPath = base_path('.env');

        if (! file_exists($envPath)) {
            return;
        }

        $content  = file_get_contents($envPath);
        $modified = false;

        if (preg_match('/^BROADCAST_CONNECTION=/m', $content)) {
            $updated = preg_replace('/^BROADCAST_CONNECTION=.*$/m', 'BROADCAST_CONNECTION=reverb', $content);
            if ($updated !== $content) {
                $content  = $updated;
                $modified = true;
            }
        }

        $vars = [
            'REVERB_APP_ID'        => 'maestro',
            'REVERB_APP_KEY'       => 'maestro-key',
            'REVERB_APP_SECRET'    => 'maestro-secret',
            'REVERB_HOST'          => 'localhost',
            'REVERB_PORT'          => '8080',
            'REVERB_SCHEME'        => 'http',
            'VITE_REVERB_APP_KEY'  => '${REVERB_APP_KEY}',
            'VITE_REVERB_HOST'     => '${REVERB_HOST}',
            'VITE_REVERB_PORT'     => '${REVERB_PORT}',
            'VITE_REVERB_SCHEME'   => '${REVERB_SCHEME}',
        ];

        $additions = [];

        if (! preg_match('/^BROADCAST_CONNECTION=/m', $content)) {
            $additions[] = 'BROADCAST_CONNECTION=reverb';
        }

        foreach ($vars as $key => $value) {
            if (! str_contains($content, $key)) {
                $additions[] = "{$key}={$value}";
            }
        }

        if (! empty($additions)) {
            $content .= "\n# Maestro / Reverb\n" . implode("\n", $additions) . "\n";
            $modified = true;
        }

        if ($modified) {
            file_put_contents($envPath, $content);
        }
    }
}
