<?php

namespace App\Commands;

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

class SeedContext extends BaseCommand
{
    protected $group       = 'Database';
    protected $name        = 'db:seed-context';
    protected $description = 'Run seeders based on APP_CONTEXT (superadmin or admin)';
    protected $usage       = 'db:seed-context [options]';
    protected $arguments   = [];
    protected $options     = [
        '--context' => 'Force a specific context (superadmin or admin)',
    ];

    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;
        }
        
        CLI::write("Running seeder 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);
        
        try {
            if ($context === 'superadmin') {
                $seederClass = new \App\Database\Seeds\SuperAdmin\SuperAdminSeeder(new \Config\Database());
            } else {
                $seederClass = new \App\Database\Seeds\Admin\AdminSeeder(new \Config\Database());
            }
            // Override the db property with our custom connection
            $reflection = new \ReflectionClass($seederClass);
            $dbProperty = $reflection->getProperty('db');
            $dbProperty->setAccessible(true);
            $dbProperty->setValue($seederClass, $db);
            
            $seederClass->run();
            CLI::newLine();
            CLI::write(CLI::color('Seeding completed!', 'green'));
        } catch (\Exception $e) {
            CLI::error('Seeding failed: ' . $e->getMessage());
        }
    }
}
