<?php
namespace App\Commands;

use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;

class DbCheck extends BaseCommand
{
    protected $group = 'Database';
    protected $name = 'db:check';
    protected $description = 'Check database connectivity using current environment configuration.';
    protected $usage = 'db:check [--group default] [--show]';

    public function run(array $params)
    {
        $group = CLI::getOption('group') ?? CLI::getOption('g') ?? 'default';
        $show = CLI::getOption('show') !== null;

        $config = config('Database');
        $settings = $config->$group ?? null;
        if ($settings === null) {
            CLI::error("Database group '{$group}' not found.");
            return;
        }

        if ($show) {
            $driver = is_array($settings) ? ($settings['DBDriver'] ?? '') : ($settings->DBDriver ?? '');
            $host = is_array($settings) ? ($settings['hostname'] ?? '') : ($settings->hostname ?? '');
            $port = is_array($settings) ? ($settings['port'] ?? '') : ($settings->port ?? '');
            $database = is_array($settings) ? ($settings['database'] ?? '') : ($settings->database ?? '');
            $username = is_array($settings) ? ($settings['username'] ?? '') : ($settings->username ?? '');
            $dsn = is_array($settings) ? ($settings['DSN'] ?? '') : ($settings->DSN ?? '');
            $maskedUser = $username ? substr($username, 0, 1) . str_repeat('*', max(0, strlen($username) - 2)) . substr($username, -1) : '';
            $maskedDb = $database ? substr($database, 0, 1) . str_repeat('*', max(0, strlen($database) - 2)) . substr($database, -1) : '';
            CLI::write("Group: {$group}");
            CLI::write("Driver: {$driver}");
            CLI::write("Host: {$host}" . ($port ? ":{$port}" : ''));
            CLI::write("Database: {$maskedDb}");
            CLI::write("Username: {$maskedUser}");
            if ($dsn) {
                CLI::write("DSN: {$dsn}");
            }
        }

        try {
            $db = \Config\Database::connect($group, false);
            $db->connect();
            $platform = $db->getPlatform();
            $version = $db->getVersion();
            $db->query('SELECT 1');
            CLI::write("Connection successful: {$platform} {$version}", 'green');
        } catch (\Throwable $e) {
            CLI::error('Connection failed: ' . $e->getMessage());
        }
    }
}

