<?php

namespace App\Commands;

use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use Config\Deployment;

class MigrateContext extends BaseCommand
{
    protected $group       = 'Database';
    protected $name        = 'migrate:context';
    protected $description = 'Run migrations based on APP_CONTEXT (superadmin or admin)';
    protected $usage       = 'migrate:context [options]';
    protected $arguments   = [];
    protected $options     = [
        '--context' => 'Force a specific context (superadmin or admin)',
        '--rollback' => 'Rollback migrations instead of running them',
    ];

    public function run(array $params)
    {
        $deployment = config('Deployment');
        $context = CLI::getOption('context');
        
        if (!$context) {
            $context = $deployment->isSuperAdmin() ? 'superadmin' : 'admin';
        }
        
        $context = strtolower($context);
        
        if (!in_array($context, ['superadmin', 'admin'])) {
            CLI::error('Invalid context. Must be "superadmin" or "admin".');
            return;
        }
        
        $rollback = CLI::getOption('rollback') !== null;
        
        CLI::write("Running migrations for context: " . CLI::color(strtoupper($context), 'green'));
        CLI::newLine();
        
        // Build custom database config for the specified context
        $dbName = $context === 'superadmin' 
            ? env('SUPERADMIN_DB_NAME', '') 
            : env('ADMIN_DB_NAME', '');
        
        $customConfig = [
            'DSN'          => '',
            'hostname'     => env('MYSQL_HOST', 'localhost'),
            'username'     => env('MYSQL_USERNAME', ''),
            'password'     => env('MYSQL_PASSWORD', ''),
            'database'     => $dbName,
            'DBDriver'     => 'MySQLi',
            'DBPrefix'     => '',
            'pConnect'     => false,
            'DBDebug'      => true,
            'charset'      => 'utf8mb4',
            'DBCollat'     => 'utf8mb4_general_ci',
            'swapPre'      => '',
            'encrypt'      => false,
            'compress'     => false,
            'strictOn'     => false,
            'failover'     => [],
            'port'         => (int) env('MYSQL_PORT', '3306'),
            'numberNative' => false,
            'foundRows'    => false,
            'dateFormat'   => [
                'date'     => 'Y-m-d',
                'datetime' => 'Y-m-d H:i:s',
                'time'     => 'H:i:s',
            ],
        ];
        
        CLI::write("Using database: " . CLI::color($dbName, 'yellow'));
        CLI::newLine();
        
        // Create a new database connection with custom config
        $db = \Config\Database::connect($customConfig);
        
        $migrationPath = $context === 'superadmin' ? 'SuperAdmin' : 'Admin';
        
        try {
            // Get the forge from the connection
            $forge = \Config\Database::forge($db);
            
            if ($rollback) {
                CLI::write('Rolling back migrations...');
                
                if ($context === 'superadmin') {
                    $migration = new \App\Database\Migrations\SuperAdmin\CreateSuperAdminTables($forge);
                } else {
                    $migration = new \App\Database\Migrations\Admin\CreateAdminTables($forge);
                }
                $migration->down();
                CLI::write(CLI::color('Rollback completed successfully!', 'green'));
            } else {
                CLI::write('Running migrations...');
                
                if ($context === 'superadmin') {
                    $migration = new \App\Database\Migrations\SuperAdmin\CreateSuperAdminTables($forge);
                } else {
                    $migration = new \App\Database\Migrations\Admin\CreateAdminTables($forge);
                }
                $migration->up();
                CLI::write(CLI::color('Migrations completed successfully!', 'green'));
            }
        } catch (\Exception $e) {
            CLI::error('Migration failed: ' . $e->getMessage());
            return;
        }
        
        CLI::newLine();
        CLI::write('Database tables for ' . strtoupper($context) . ' deployment are ready.');
        
        if ($context === 'superadmin') {
            CLI::write('Tables created: super_admins, license_keys, reported_systems, audit_logs');
            CLI::newLine();
            CLI::write('Next step: Run "php spark db:seed-context --context=superadmin" to create default super admin');
        } else {
            CLI::write('Tables created: admins, license_keys, admin_settings, users, registered_systems, admin_license_cache, system_usage, audit_logs');
            CLI::newLine();
            CLI::write('Next step: Configure your .env with Super Admin API URL and register your admin account');
        }
    }
}
