<?php

namespace App\Modules\Product\Solusvm;

use App\Core\Product\AbstractProduct;
use App\Core\Product\Events\AccountCreated;
use Illuminate\Support\Facades\Log;

class Solusvm extends AbstractProduct
{
    /**
     * SolusVM API port (default admin port)
     */
    protected $apiPort = 5656;

    /**
     * SolusVM modulu server gerektirir
     */
    public function requiresServer(): bool
    {
        return true;
    }

    /**
     * Uzak SolusVM sanal sunucu kimligini cozer.
     *
     * PRC-1015: once kanonik remoteId($params) (account_id/module_handler_id),
     * yoksa client-field olarak saklanan vserver_id fallback. Ic procp FK
     * (server_id/client_id) ASLA uzak-id olarak kullanilmaz.
     */
    protected function resolveVserverId(array $params): ?string
    {
        $remote = $this->remoteId($params);
        if ($remote !== null && $remote !== '') {
            return $remote;
        }

        if (! empty($params['vserver_id'])) {
            return (string) $params['vserver_id'];
        }

        return null;
    }

    /**
     * Yeni bir SolusVM sanal sunucu olusturur (vserver-create)
     *
     * @param  array  $params  Parametreler
     * @return array Islem sonucu
     */
    public function createAccount(array $params)
    {
        // Plan/template flat: builder module-config'ten emit eder; yoksa config-option
        // ya da module-config fallback. type/ips/node de ayni sirayla cozulur.
        $plan = $params['plan']
            ?? $params['package']
            ?? $this->configOption($params, 'plan')
            ?? $this->moduleConfig($params, 'plan');

        $template = $params['template']
            ?? $this->configOption($params, 'template')
            ?? $this->moduleConfig($params, 'template');

        $type = $params['type']
            ?? $this->configOption($params, 'type')
            ?? $this->moduleConfig($params, 'type', 'kvm');

        $ips = $params['ips']
            ?? $this->configOption($params, 'ips')
            ?? $this->moduleConfig($params, 'ips', '1');

        // hostname = VPS hostname (client-field), password = root sifresi.
        $required = [
            'hostname' => $params['hostname'] ?? null,
            'password' => $params['password'] ?? null,
            'plan' => $plan,
            'template' => $template,
        ];

        foreach ($required as $name => $value) {
            if (empty($value)) {
                return [
                    'status' => 'error',
                    'message' => __('admin/modules.solusvm_param_missing', ['param' => $name]),
                ];
            }
        }

        $apiParams = [
            'hostname' => $params['hostname'],
            'password' => $params['password'],
            'username' => $params['username'] ?? '',
            'plan' => $plan,
            'template' => $template,
            'type' => $type,
            'ips' => $ips,
        ];

        // Node veya nodegroup parametresi (config-option/module-config uzerinden de gelebilir)
        $node = $params['node'] ?? $this->configOption($params, 'node') ?? $this->moduleConfig($params, 'node');
        if (! empty($node)) {
            $apiParams['node'] = $node;
        }

        $nodegroup = $params['nodegroup'] ?? $this->configOption($params, 'nodegroup') ?? $this->moduleConfig($params, 'nodegroup');
        if (! empty($nodegroup)) {
            $apiParams['nodegroup'] = $nodegroup;
        }

        $response = $this->callSolus('vserver-create', $apiParams, $params);

        if ($response['status'] === 'success') {
            $result = [
                'status' => 'success',
                'message' => __('admin/modules.solusvm_account_created_success'),
                'data' => $response['data'] ?? [],
            ];

            AccountCreated::dispatch($params, $result);

            return $result;
        }

        $result = [
            'status' => 'error',
            'message' => $response['message'] ?? __('admin/modules.solusvm_account_create_failed'),
            'data' => $response['data'] ?? [],
        ];

        AccountCreated::dispatch($params, $result);

        return $result;
    }

    /**
     * Bir SolusVM sanal sunucuyu askiya alir (vserver-suspend)
     *
     * @param  array  $params  Parametreler
     * @return array Islem sonucu
     */
    public function suspendAccount(array $params)
    {
        $vserverId = $this->resolveVserverId($params);
        if ($vserverId === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.solusvm_vserverid_required'),
            ];
        }

        $response = $this->callSolus('vserver-suspend', [
            'vserverid' => $vserverId,
        ], $params);

        if ($response['status'] === 'success') {
            return [
                'status' => 'success',
                'message' => __('admin/modules.solusvm_account_suspended_success'),
            ];
        }

        return [
            'status' => 'error',
            'message' => $response['message'] ?? __('admin/modules.solusvm_account_suspend_failed'),
            'data' => $response['data'] ?? [],
        ];
    }

    /**
     * Askiya alinmis bir SolusVM sanal sunucuyu aktiflestirir (vserver-unsuspend)
     *
     * @param  array  $params  Parametreler
     * @return array Islem sonucu
     */
    public function unsuspendAccount(array $params)
    {
        $vserverId = $this->resolveVserverId($params);
        if ($vserverId === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.solusvm_vserverid_required'),
            ];
        }

        $response = $this->callSolus('vserver-unsuspend', [
            'vserverid' => $vserverId,
        ], $params);

        if ($response['status'] === 'success') {
            return [
                'status' => 'success',
                'message' => __('admin/modules.solusvm_account_unsuspended_success'),
            ];
        }

        return [
            'status' => 'error',
            'message' => $response['message'] ?? __('admin/modules.solusvm_account_unsuspend_failed'),
            'data' => $response['data'] ?? [],
        ];
    }

    /**
     * Bir SolusVM sanal sunucuyu sonlandirir (vserver-terminate)
     *
     * @param  array  $params  Parametreler
     * @return array Islem sonucu
     */
    public function terminateAccount(array $params)
    {
        $vserverId = $this->resolveVserverId($params);
        if ($vserverId === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.solusvm_vserverid_required'),
            ];
        }

        $response = $this->callSolus('vserver-terminate', [
            'vserverid' => $vserverId,
            'deleteclient' => 'true',
        ], $params);

        if ($response['status'] === 'success') {
            return [
                'status' => 'success',
                'message' => __('admin/modules.solusvm_account_terminated_success'),
            ];
        }

        return [
            'status' => 'error',
            'message' => $response['message'] ?? __('admin/modules.solusvm_account_terminate_failed'),
            'data' => $response['data'] ?? [],
        ];
    }

    /**
     * Bir SolusVM sanal sunucunun root sifresini degistirir (vserver-rootpassword)
     *
     * @param  array  $params  Parametreler
     * @return array Islem sonucu
     */
    public function changeAccountPassword(array $params)
    {
        $vserverId = $this->resolveVserverId($params);
        if ($vserverId === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.solusvm_vserverid_required'),
            ];
        }

        if (! isset($params['password']) || empty($params['password'])) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.solusvm_password_required'),
            ];
        }

        $response = $this->callSolus('vserver-rootpassword', [
            'vserverid' => $vserverId,
            'rootpassword' => $params['password'],
        ], $params);

        if ($response['status'] === 'success') {
            return [
                'status' => 'success',
                'message' => __('admin/modules.solusvm_password_changed_success'),
            ];
        }

        return [
            'status' => 'error',
            'message' => $response['message'] ?? __('admin/modules.solusvm_password_change_failed'),
            'data' => $response['data'] ?? [],
        ];
    }

    /**
     * Bir SolusVM sanal sunucunun planini degistirir (vserver-change)
     *
     * @param  array  $params  Parametreler
     * @return array Islem sonucu
     */
    public function changeAccountPackage(array $params)
    {
        $vserverId = $this->resolveVserverId($params);
        if ($vserverId === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.solusvm_vserverid_required'),
            ];
        }

        // Plan flat: $params['plan']/$params['package'] (builder emit) → config-option → module-config
        $plan = $params['plan']
            ?? $params['package']
            ?? $this->configOption($params, 'plan')
            ?? $this->moduleConfig($params, 'plan');

        if (empty($plan)) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.solusvm_plan_required'),
            ];
        }

        $response = $this->callSolus('vserver-change', [
            'vserverid' => $vserverId,
            'plan' => $plan,
        ], $params);

        if ($response['status'] === 'success') {
            return [
                'status' => 'success',
                'message' => __('admin/modules.solusvm_package_changed_success'),
            ];
        }

        return [
            'status' => 'error',
            'message' => $response['message'] ?? __('admin/modules.solusvm_package_change_failed'),
            'data' => $response['data'] ?? [],
        ];
    }

    /**
     * Baglanti testini gerceklestirir (listnodes)
     *
     * @param  array  $params  Test parametreleri
     * @return array Test sonucu
     */
    public function testConnection(array $params = [])
    {
        $response = $this->callSolus('listnodes', [
            'type' => $params['type'] ?? 'kvm',
        ], $params);

        if ($response['status'] === 'success') {
            return [
                'status' => 'success',
                'message' => __('admin/modules.solusvm_connection_test_success'),
                'data' => $response['data'] ?? [],
            ];
        }

        return [
            'status' => 'error',
            'message' => $response['message'] ?? __('admin/modules.solusvm_connection_test_failed'),
            'data' => $response['data'] ?? [],
        ];
    }

    /**
     * Admin panelinde gosterilecek alanlari dondurur
     *
     * @return array Admin panel alanlari
     */
    public function adminFields()
    {
        return [
            'hostname' => [
                'name' => __('admin/modules.solusvm_field_hostname'),
                'type' => 'text',
                'description' => __('admin/modules.solusvm_field_hostname_description'),
                'required' => true,
            ],
            'port' => [
                'name' => __('admin/modules.solusvm_field_port'),
                'type' => 'text',
                'description' => __('admin/modules.solusvm_field_port_description'),
                'default' => '5656',
                'required' => false,
            ],
            'api_id' => [
                'name' => __('admin/modules.solusvm_field_api_id'),
                'type' => 'text',
                'description' => __('admin/modules.solusvm_field_api_id_description'),
                'required' => true,
            ],
            'api_key' => [
                'name' => __('admin/modules.solusvm_field_api_key'),
                'type' => 'password',
                'description' => __('admin/modules.solusvm_field_api_key_description'),
                'required' => true,
            ],
            'use_ssl' => [
                'name' => __('admin/modules.solusvm_field_use_ssl'),
                'type' => 'checkbox',
                'description' => __('admin/modules.solusvm_field_use_ssl_description'),
                'default' => true,
            ],
        ];
    }

    /**
     * Musteri panelinde gosterilecek alanlari dondurur
     *
     * @return array Musteri panel alanlari
     */
    public function clientFields()
    {
        return [
            'hostname' => [
                'name' => __('admin/modules.solusvm_field_client_hostname'),
                'type' => 'text',
                'description' => __('admin/modules.solusvm_field_client_hostname_description'),
                'required' => true,
            ],
            'vserver_id' => [
                'name' => __('admin/modules.solusvm_field_vserver_id'),
                'type' => 'text',
                'description' => __('admin/modules.solusvm_field_vserver_id_description'),
                'required' => true,
            ],
        ];
    }

    /**
     * Server yonetimi icin gosterilecek alanlari dondurur
     *
     * @return array Server yonetimi alanlari
     */
    public function serverFields()
    {
        return [
            'api_id' => [
                'name' => __('admin/modules.solusvm_field_api_id'),
                'type' => 'text',
                'description' => __('admin/modules.solusvm_field_api_id_description'),
                'required' => true,
            ],
            'api_key' => [
                'name' => __('admin/modules.solusvm_field_api_key'),
                'type' => 'password',
                'description' => __('admin/modules.solusvm_field_api_key_description'),
                'required' => true,
            ],
        ];
    }

    /**
     * Admin panelde gosterilecek ozel butonlari dondurur
     *
     * @return array Admin butonlari
     */
    public function getAdminButtons(): array
    {
        return [
            [
                'action' => 'list_nodes',
                'label' => __('admin/modules.solusvm_action_list_nodes'),
                'icon' => 'fas fa-server',
                'class' => 'btn-outline-info',
            ],
            [
                'action' => 'list_plans',
                'label' => __('admin/modules.solusvm_action_list_plans'),
                'icon' => 'fas fa-list',
                'class' => 'btn-outline-info',
            ],
            [
                'action' => 'list_templates',
                'label' => __('admin/modules.solusvm_action_list_templates'),
                'icon' => 'fas fa-clone',
                'class' => 'btn-outline-info',
            ],
            [
                'action' => 'server_info',
                'label' => __('admin/modules.solusvm_action_server_info'),
                'icon' => 'fas fa-info-circle',
                'class' => 'btn-outline-primary',
            ],
            [
                'action' => 'reboot',
                'label' => __('admin/modules.solusvm_action_reboot'),
                'icon' => 'fas fa-sync',
                'class' => 'btn-outline-warning',
            ],
        ];
    }

    /**
     * Admin ozel action'i isler
     *
     * @param  string  $action  Action adi
     * @param  array  $params  Parametreler
     * @return array Islem sonucu
     */
    public function adminCustomAction(string $action, array $params): array
    {
        switch ($action) {
            case 'list_nodes':
                return $this->actionListNodes($params);

            case 'list_plans':
                return $this->actionListPlans($params);

            case 'list_templates':
                return $this->actionListTemplates($params);

            case 'server_info':
                return $this->actionServerInfo($params);

            case 'reboot':
                return $this->actionVserverReboot($params);

            case 'boot':
                return $this->actionVserverBoot($params);

            case 'shutdown':
                return $this->actionVserverShutdown($params);

            default:
                return [
                    'status' => 'error',
                    'message' => __('admin/modules.solusvm_action_not_supported', ['action' => $action]),
                ];
        }
    }

    /**
     * Client area'da gosterilecek action'lari dondurur
     *
     * @return array Client action'lari
     */
    public function getClientActions(): array
    {
        $actions = parent::getClientActions();

        $actions['reboot'] = [
            'label' => __('admin/modules.solusvm_client_action_reboot'),
            'icon' => 'fas fa-sync',
            'class' => 'btn-outline-warning',
            'enabled' => true,
        ];

        $actions['boot'] = [
            'label' => __('admin/modules.solusvm_client_action_boot'),
            'icon' => 'fas fa-play',
            'class' => 'btn-outline-success',
            'enabled' => true,
        ];

        $actions['shutdown'] = [
            'label' => __('admin/modules.solusvm_client_action_shutdown'),
            'icon' => 'fas fa-power-off',
            'class' => 'btn-outline-danger',
            'enabled' => true,
        ];

        $actions['console'] = [
            'label' => __('admin/modules.solusvm_client_action_console'),
            'icon' => 'fas fa-terminal',
            'class' => 'btn-outline-info',
            'enabled' => true,
        ];

        return $actions;
    }

    /**
     * Client action'i isler
     *
     * @param  string  $action  Action adi
     * @param  array  $params  Parametreler
     * @return array Sonuc
     */
    public function handleClientAction(string $action, array $params): array
    {
        switch ($action) {
            case 'reboot':
                return $this->clientActionReboot($params);

            case 'boot':
                return $this->clientActionBoot($params);

            case 'shutdown':
                return $this->clientActionShutdown($params);

            case 'console':
                return $this->clientActionConsole($params);

            default:
                return parent::handleClientAction($action, $params);
        }
    }

    /**
     * Kaynak kullanim bilgilerini dondurur (vserver-infoall ile bandwidth, disk, memory)
     *
     * @param  array  $params  Parametreler (vserver_id gerekli)
     * @return array|null Kaynak kullanim verileri veya null
     */
    public function getResourceUsage(array $params): ?array
    {
        $vserverId = $this->resolveVserverId($params);
        if ($vserverId === null) {
            return null;
        }

        $response = $this->callSolus('vserver-infoall', [
            'vserverid' => $vserverId,
        ], $params);

        if ($response['status'] !== 'success' || empty($response['data'])) {
            return null;
        }

        $data = $response['data'];
        $resources = [];

        // Bandwidth kullanimi (bytes -> GB)
        $bwUsed = isset($data['bandwidth']) ? round((float) $data['bandwidth'] / 1073741824, 2) : 0;
        $bwLimit = isset($data['limit']) ? round((float) $data['limit'] / 1073741824, 2) : 0;
        $bwPercentage = $bwLimit > 0 ? round(($bwUsed / $bwLimit) * 100, 2) : 0;

        $resources[] = [
            'name' => 'Bandwidth',
            'used' => $bwUsed,
            'limit' => $bwLimit,
            'unit' => 'GB',
            'percentage' => $bwPercentage,
        ];

        // Disk kullanimi (bytes -> GB)
        $diskUsed = isset($data['hdd']) ? round((float) $data['hdd'] / 1073741824, 2) : 0;
        $diskLimit = isset($data['hdlimit']) ? round((float) $data['hdlimit'] / 1073741824, 2) : 0;
        $diskPercentage = $diskLimit > 0 ? round(($diskUsed / $diskLimit) * 100, 2) : 0;

        $resources[] = [
            'name' => 'Disk Space',
            'used' => $diskUsed,
            'limit' => $diskLimit,
            'unit' => 'GB',
            'percentage' => $diskPercentage,
        ];

        // Memory kullanimi (bytes -> MB)
        $memUsed = isset($data['mem']) ? round((float) $data['mem'] / 1048576, 2) : 0;
        $memLimit = isset($data['memlimit']) ? round((float) $data['memlimit'] / 1048576, 2) : 0;
        $memPercentage = $memLimit > 0 ? round(($memUsed / $memLimit) * 100, 2) : 0;

        $resources[] = [
            'name' => 'Memory',
            'used' => $memUsed,
            'limit' => $memLimit,
            'unit' => 'MB',
            'percentage' => $memPercentage,
        ];

        return $resources;
    }

    /**
     * Yapilandirma dogrulamasi
     *
     * @return bool Yapilandirma dogru mu?
     *
     * @throws \Exception Eksik yapilandirma durumunda
     */
    public function validateConfig()
    {
        if (empty($this->config['hostname'])) {
            throw new \Exception(__('admin/modules.solusvm_config_hostname_missing'));
        }

        if (empty($this->config['api_id'])) {
            throw new \Exception(__('admin/modules.solusvm_config_api_id_missing'));
        }

        if (empty($this->config['api_key'])) {
            throw new \Exception(__('admin/modules.solusvm_config_api_key_missing'));
        }

        return true;
    }

    // ─── Admin Custom Action Handlers ────────────────────────────────────

    /**
     * Node listesini getirir (listnodes)
     */
    protected function actionListNodes(array $params): array
    {
        $response = $this->callSolus('listnodes', [
            'type' => $params['type'] ?? 'kvm',
        ], $params);

        if ($response['status'] !== 'success') {
            return [
                'status' => 'error',
                'message' => $response['message'] ?? __('admin/modules.solusvm_list_nodes_failed'),
            ];
        }

        $nodes = [];
        if (! empty($response['data']['nodes'])) {
            $nodeNames = explode(',', $response['data']['nodes']);
            $nodeIds = ! empty($response['data']['nodeids']) ? explode(',', $response['data']['nodeids']) : [];

            foreach ($nodeNames as $index => $name) {
                $nodes[] = [
                    'name' => trim($name),
                    'id' => isset($nodeIds[$index]) ? trim($nodeIds[$index]) : '',
                ];
            }
        }

        return [
            'status' => 'success',
            'message' => __('admin/modules.solusvm_list_nodes_success'),
            'data' => $nodes,
        ];
    }

    /**
     * Plan listesini getirir (listplans)
     */
    protected function actionListPlans(array $params): array
    {
        $response = $this->callSolus('listplans', [
            'type' => $params['type'] ?? 'kvm',
        ], $params);

        if ($response['status'] !== 'success') {
            return [
                'status' => 'error',
                'message' => $response['message'] ?? __('admin/modules.solusvm_list_plans_failed'),
            ];
        }

        $plans = [];
        if (! empty($response['data']['plans'])) {
            $planNames = explode(',', $response['data']['plans']);
            $planIds = ! empty($response['data']['planids']) ? explode(',', $response['data']['planids']) : [];

            foreach ($planNames as $index => $name) {
                $plans[] = [
                    'name' => trim($name),
                    'id' => isset($planIds[$index]) ? trim($planIds[$index]) : '',
                ];
            }
        }

        return [
            'status' => 'success',
            'message' => __('admin/modules.solusvm_list_plans_success'),
            'data' => $plans,
        ];
    }

    /**
     * Template listesini getirir (listtemplates)
     */
    protected function actionListTemplates(array $params): array
    {
        $response = $this->callSolus('listtemplates', [
            'type' => $params['type'] ?? 'kvm',
        ], $params);

        if ($response['status'] !== 'success') {
            return [
                'status' => 'error',
                'message' => $response['message'] ?? __('admin/modules.solusvm_list_templates_failed'),
            ];
        }

        $templates = [];
        if (! empty($response['data']['templates'])) {
            $templateNames = explode(',', $response['data']['templates']);
            $templateIds = ! empty($response['data']['templateids']) ? explode(',', $response['data']['templateids']) : [];

            foreach ($templateNames as $index => $name) {
                $templates[] = [
                    'name' => trim($name),
                    'id' => isset($templateIds[$index]) ? trim($templateIds[$index]) : '',
                ];
            }
        }

        return [
            'status' => 'success',
            'message' => __('admin/modules.solusvm_list_templates_success'),
            'data' => $templates,
        ];
    }

    /**
     * Sanal sunucu bilgilerini getirir (vserver-infoall)
     */
    protected function actionServerInfo(array $params): array
    {
        $vserverId = $this->resolveVserverId($params);
        if ($vserverId === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.solusvm_vserverid_required'),
            ];
        }

        $response = $this->callSolus('vserver-infoall', [
            'vserverid' => $vserverId,
        ], $params);

        if ($response['status'] !== 'success') {
            return [
                'status' => 'error',
                'message' => $response['message'] ?? __('admin/modules.solusvm_server_info_failed'),
            ];
        }

        $data = $response['data'];

        return [
            'status' => 'success',
            'message' => __('admin/modules.solusvm_server_info_success'),
            'data' => [
                'hostname' => $data['hostname'] ?? '',
                'main_ip' => $data['mainipaddress'] ?? '',
                'state' => $data['state'] ?? '',
                'type' => $data['type'] ?? '',
                'node' => $data['node'] ?? '',
                'plan' => $data['plan'] ?? '',
                'template' => $data['template'] ?? '',
                'bandwidth_used' => $data['bandwidth'] ?? '0',
                'bandwidth_limit' => $data['limit'] ?? '0',
                'hdd_used' => $data['hdd'] ?? '0',
                'hdd_limit' => $data['hdlimit'] ?? '0',
                'memory_used' => $data['mem'] ?? '0',
                'memory_limit' => $data['memlimit'] ?? '0',
            ],
        ];
    }

    /**
     * Sanal sunucuyu yeniden baslatir (vserver-reboot)
     */
    protected function actionVserverReboot(array $params): array
    {
        $vserverId = $this->resolveVserverId($params);
        if ($vserverId === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.solusvm_vserverid_required'),
            ];
        }

        $response = $this->callSolus('vserver-reboot', [
            'vserverid' => $vserverId,
        ], $params);

        if ($response['status'] === 'success') {
            return [
                'status' => 'success',
                'message' => __('admin/modules.solusvm_reboot_success'),
            ];
        }

        return [
            'status' => 'error',
            'message' => $response['message'] ?? __('admin/modules.solusvm_reboot_failed'),
            'data' => $response['data'] ?? [],
        ];
    }

    /**
     * Sanal sunucuyu baslatir (vserver-boot)
     */
    protected function actionVserverBoot(array $params): array
    {
        $vserverId = $this->resolveVserverId($params);
        if ($vserverId === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.solusvm_vserverid_required'),
            ];
        }

        $response = $this->callSolus('vserver-boot', [
            'vserverid' => $vserverId,
        ], $params);

        if ($response['status'] === 'success') {
            return [
                'status' => 'success',
                'message' => __('admin/modules.solusvm_boot_success'),
            ];
        }

        return [
            'status' => 'error',
            'message' => $response['message'] ?? __('admin/modules.solusvm_boot_failed'),
            'data' => $response['data'] ?? [],
        ];
    }

    /**
     * Sanal sunucuyu kapatir (vserver-shutdown)
     */
    protected function actionVserverShutdown(array $params): array
    {
        $vserverId = $this->resolveVserverId($params);
        if ($vserverId === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.solusvm_vserverid_required'),
            ];
        }

        $response = $this->callSolus('vserver-shutdown', [
            'vserverid' => $vserverId,
        ], $params);

        if ($response['status'] === 'success') {
            return [
                'status' => 'success',
                'message' => __('admin/modules.solusvm_shutdown_success'),
            ];
        }

        return [
            'status' => 'error',
            'message' => $response['message'] ?? __('admin/modules.solusvm_shutdown_failed'),
            'data' => $response['data'] ?? [],
        ];
    }

    // ─── Client Action Handlers ──────────────────────────────────────────

    /**
     * Client: VPS yeniden baslatma
     */
    protected function clientActionReboot(array $params): array
    {
        $vserverId = $this->resolveVserverId($params);
        if ($vserverId === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.solusvm_vserverid_required'),
            ];
        }

        $response = $this->callSolus('vserver-reboot', [
            'vserverid' => $vserverId,
        ], $params);

        if ($response['status'] === 'success') {
            return [
                'status' => 'success',
                'message' => __('admin/modules.solusvm_client_reboot_success'),
            ];
        }

        return [
            'status' => 'error',
            'message' => $response['message'] ?? __('admin/modules.solusvm_client_reboot_failed'),
        ];
    }

    /**
     * Client: VPS baslatma
     */
    protected function clientActionBoot(array $params): array
    {
        $vserverId = $this->resolveVserverId($params);
        if ($vserverId === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.solusvm_vserverid_required'),
            ];
        }

        $response = $this->callSolus('vserver-boot', [
            'vserverid' => $vserverId,
        ], $params);

        if ($response['status'] === 'success') {
            return [
                'status' => 'success',
                'message' => __('admin/modules.solusvm_client_boot_success'),
            ];
        }

        return [
            'status' => 'error',
            'message' => $response['message'] ?? __('admin/modules.solusvm_client_boot_failed'),
        ];
    }

    /**
     * Client: VPS kapatma
     */
    protected function clientActionShutdown(array $params): array
    {
        $vserverId = $this->resolveVserverId($params);
        if ($vserverId === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.solusvm_vserverid_required'),
            ];
        }

        $response = $this->callSolus('vserver-shutdown', [
            'vserverid' => $vserverId,
        ], $params);

        if ($response['status'] === 'success') {
            return [
                'status' => 'success',
                'message' => __('admin/modules.solusvm_client_shutdown_success'),
            ];
        }

        return [
            'status' => 'error',
            'message' => $response['message'] ?? __('admin/modules.solusvm_client_shutdown_failed'),
        ];
    }

    /**
     * Client: VNC/noVNC konsol erisimi (vserver-vnc)
     */
    protected function clientActionConsole(array $params): array
    {
        $vserverId = $this->resolveVserverId($params);
        if ($vserverId === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.solusvm_vserverid_required'),
            ];
        }

        $response = $this->callSolus('vserver-vnc', [
            'vserverid' => $vserverId,
        ], $params);

        if ($response['status'] === 'success' && ! empty($response['data'])) {
            $data = $response['data'];

            // Host serverConfig'ten cozulur (inline $this->config KALDIRILDI).
            $cfg = $this->serverConfig($params);
            $hostname = $data['vncip'] ?? $cfg['hostname'];
            $port = $data['vncport'] ?? '';
            $vncPassword = $data['vncpassword'] ?? '';

            return [
                'status' => 'success',
                'message' => __('admin/modules.solusvm_console_success'),
                'data' => [
                    'type' => 'vnc',
                    'ip' => $hostname,
                    'port' => $port,
                    'password' => $vncPassword,
                ],
            ];
        }

        return [
            'status' => 'error',
            'message' => $response['message'] ?? __('admin/modules.solusvm_console_failed'),
        ];
    }

    // ─── API Helper ──────────────────────────────────────────────────────

    /**
     * SolusVM API'sine istek gonderir
     *
     * POST istegi: https://{hostname}:{port}/api/admin/command.php
     * Kimlik dogrulama: id + key POST parametreleri
     * Basari kontrolu: status=success veya status=error
     *
     * Host/kimlik bilgileri DAİMA serverConfig($moduleParams) üzerinden çözülür
     * (atanmış sunucu öncelikli, yoksa module_config). SolusVM iki parçalı kimlik
     * kullanır: `id` (api_id → moduleConfig) + `key` (api_key → serverConfig password).
     *
     * @param  string  $action  SolusVM API action (vserver-create, vserver-suspend vb.)
     * @param  array  $apiParams  Gonderilecek API parametreleri
     * @param  array  $moduleParams  Module builder params (host/creds çözümü için)
     * @return array API yaniti ['status' => 'success|error', 'message' => '...', 'data' => [...]]
     */
    protected function callSolus(string $action, array $apiParams = [], array $moduleParams = []): array
    {
        $cfg = $this->serverConfig($moduleParams);

        $hostname = trim((string) $cfg['hostname']);
        $port = $cfg['port'] ?: ($this->moduleConfig($moduleParams, 'port', null) ?: $this->apiPort);
        $protocol = ((bool) $cfg['secure']) ? 'https' : 'http';

        // SolusVM `key` = serverConfig password (api_key alanlarından toplanır).
        $apiKey = (string) $cfg['password'];
        // SolusVM `id` = api_id (hash id) — password DEĞİL, ayrı module-config anahtarı.
        $apiId = (string) ($this->moduleConfig($moduleParams, 'api_id', $cfg['username']) ?? '');

        if ($hostname === '' || $apiId === '' || $apiKey === '') {
            return [
                'status' => 'error',
                'message' => __('admin/modules.solusvm_config_incomplete'),
                'data' => [],
            ];
        }

        $url = "{$protocol}://{$hostname}:{$port}/api/admin/command.php";

        // API kimlik bilgileri ve action'i ekle. rdtype=json → SolusVM JSON
        // yanit doner (WiseCP referans-paritesi; parseSolusResponse JSON-once).
        $postData = array_merge([
            'id' => $apiId,
            'key' => $apiKey,
            'action' => $action,
            'rdtype' => 'json',
        ], $apiParams);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 120);

        $data = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        $curlErrno = curl_errno($ch);

        curl_close($ch);

        // cURL hatasi kontrolu
        if ($curlErrno) {
            Log::error('SolusVM API cURL error', [
                'action' => $action,
                'errno' => $curlErrno,
                'error' => $curlError,
            ]);

            return [
                'status' => 'error',
                'message' => __('admin/modules.solusvm_curl_error', [
                    'errno' => $curlErrno,
                    'error' => $curlError,
                ]),
                'data' => [],
            ];
        }

        // HTTP hata kodu kontrolu — ham yanit (kimlik/sifre sizabilir) LOGLANMAZ
        if ($httpCode >= 400) {
            Log::error('SolusVM API HTTP error', [
                'action' => $action,
                'http_code' => $httpCode,
            ]);

            return [
                'status' => 'error',
                'message' => __('admin/modules.solusvm_api_call_failed', ['code' => $httpCode]),
                'data' => [],
            ];
        }

        // SolusVM yanit formati: key1=value1\nkey2=value2
        $parsedData = $this->parseSolusResponse($data);

        // Status kontrolu
        if (isset($parsedData['status']) && $parsedData['status'] === 'success') {
            return [
                'status' => 'success',
                'message' => $parsedData['statusmsg'] ?? '',
                'data' => $parsedData,
            ];
        }

        // Hata durumu
        $errorMessage = $parsedData['statusmsg']
            ?? $parsedData['msg']
            ?? __('admin/modules.solusvm_api_unknown_error');

        // Yalniz action + hata mesaji loglanir — tam yanit (kimlik/token) LOGLANMAZ.
        Log::warning('SolusVM API error response', [
            'action' => $action,
            'statusmsg' => $errorMessage,
        ]);

        return [
            'status' => 'error',
            'message' => $errorMessage,
            'data' => $parsedData,
        ];
    }

    /**
     * SolusVM API yanitini parse eder
     *
     * rdtype=json gonderildigi icin yanit once JSON olarak cozulur (WiseCP
     * referans-paritesi); JSON degilse legacy key=value / XML formatlarina duser.
     *
     * @param  string  $response  Ham API yaniti
     * @return array Parse edilmis veriler
     */
    protected function parseSolusResponse(string $response): array
    {
        $result = [];

        if (empty($response)) {
            return $result;
        }

        $trimmed = trim($response);

        // rdtype=json → JSON yanit (flat assoc: status/statusmsg/vserverid...).
        if (str_starts_with($trimmed, '{')) {
            $decoded = json_decode($trimmed, true);
            if (is_array($decoded)) {
                foreach ($decoded as $key => $value) {
                    $result[(string) $key] = is_scalar($value) ? (string) $value : $value;
                }

                return $result;
            }
        }

        // Bazi yanitlar XML/HTML olabilir, once kontrol et
        if (str_starts_with($trimmed, '<')) {
            // XML yanit - basit parse
            $xmlResult = @simplexml_load_string($response);
            if ($xmlResult !== false) {
                foreach ($xmlResult as $key => $value) {
                    $result[(string) $key] = (string) $value;
                }

                return $result;
            }

            // XML parse edilemedi, ham veri dondur
            return ['raw_response' => $response];
        }

        // Standard key=value format
        $lines = explode("\n", $response);

        foreach ($lines as $line) {
            $line = trim($line);
            if (empty($line)) {
                continue;
            }

            $eqPos = strpos($line, '=');
            if ($eqPos !== false) {
                $key = trim(substr($line, 0, $eqPos));
                $value = trim(substr($line, $eqPos + 1));
                $result[$key] = $value;
            }
        }

        return $result;
    }
}
