<?php

if (!defined('ABSPATH')) {
    exit;
}

final class SPP_Plugin
{
    private static ?SPP_Plugin $instance = null;

    public static function instance(): SPP_Plugin
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    public function boot(): void
    {
        SPP_Activator::maybe_upgrade();

        $repository = new SPP_Repository();
        $permissions = new SPP_Permissions();
        $proxmox = $this->make_proxmox_client();
        $expiration_service = new SPP_Expiration_Service($repository, $proxmox);

        add_action('spp_expire_deployments', [$expiration_service, 'expire_due_deployments']);

        (new SPP_REST_Controller($repository, $proxmox, $expiration_service, $permissions))->register_hooks();
        (new SPP_Admin_Page($repository, $permissions, $proxmox))->register_hooks();
        (new SPP_Shortcode($permissions))->register_hooks();
    }

    private function make_proxmox_client(): SPP_Proxmox_Client
    {
        $mode = get_option('spp_proxmox_mode', 'mock');

        if ($mode === 'http') {
            return new SPP_Http_Proxmox_Client([
                'base_url' => (string) get_option('spp_proxmox_base_url', ''),
                'token_id' => (string) get_option('spp_proxmox_token_id', ''),
                'token_secret' => (string) get_option('spp_proxmox_token_secret', ''),
                'node' => (string) get_option('spp_proxmox_node', ''),
                'lxc_rootfs_storage' => (string) get_option('spp_lxc_rootfs_storage', ''),
                'lxc_bridge' => (string) get_option('spp_lxc_bridge', 'vmbr0'),
            ]);
        }

        return new SPP_Mock_Proxmox_Client();
    }
}
