<?php

namespace App\Console\Commands;

use App\Models\User;
use Illuminate\Console\Command;

class InstallApplicationCommand extends Command
{
    protected $signature = 'app:install
        {--fresh : Drop all tables and re-run all migrations}
        {--force : Force install commands in production}
        {--admin-email=admin@example.com : Super admin email}
        {--admin-phone=admin : Super admin phone}
        {--admin-nickname=admin : Super admin nickname}
        {--admin-password=admin : Super admin password}';

    protected $description = 'Install app with migration, default RBAC data, and super admin account';

    public function handle(): int
    {
        $this->components->info('Starting application installation...');

        $migrationExitCode = $this->call(
            $this->option('fresh') ? 'migrate:fresh' : 'migrate',
            ['--force' => (bool) $this->option('force')]
        );

        if ($migrationExitCode !== self::SUCCESS) {
            $this->error('Database migration failed.');

            return self::FAILURE;
        }

        $rbacExitCode = $this->call('user:manage', [
            'action' => 'init-rbac',
        ]);

        if ($rbacExitCode !== self::SUCCESS) {
            $this->error('Default RBAC initialization failed.');

            return self::FAILURE;
        }

        $adminEmail = trim((string) $this->option('admin-email'));
        $adminPhone = trim((string) $this->option('admin-phone'));
        $adminNickname = trim((string) $this->option('admin-nickname'));
        $adminPassword = (string) $this->option('admin-password');

        if ($adminEmail === '' || $adminNickname === '' || $adminPassword === '') {
            $this->error('admin-email, admin-nickname and admin-password are required.');

            return self::FAILURE;
        }

        $adminUser = User::query()->updateOrCreate(
            ['email' => $adminEmail],
            [
                'nickname' => $adminNickname,
                'phone' => $adminPhone !== '' ? $adminPhone : null,
                'password' => $adminPassword,
                'force_password_change' => false,
            ]
        );

        $setAdminExitCode = $this->call('user:manage', [
            'action' => 'set-admin',
            '--email' => $adminUser->email,
        ]);

        if ($setAdminExitCode !== self::SUCCESS) {
            $this->error('Failed to set admin role and permissions.');

            return self::FAILURE;
        }

        $this->newLine();
        $this->components->info('Application installed successfully.');
        $this->line("Admin email: {$adminUser->email}");
        if ($adminUser->phone) {
            $this->line("Admin phone: {$adminUser->phone}");
        }
        $this->line("Admin password: {$adminPassword}");

        return self::SUCCESS;
    }
}
