#!/usr/local/cpanel/3rdparty/bin/perl

#                                      Copyright 2026 WebPros International, LLC
#                                                           All rights reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited.

use cPstrict;
use Test::Cpanel::Policy;

use Test2::V0;
use Test2::Tools::Explain;
use Test2::Tools::Compare;
use Test2::Tools::Exception;
use Test2::Plugin::NoWarnings;

use Test::MockModule;
use Test::MockFile;

# Pre-load stub modules to prevent dependencies from failing
BEGIN {
    $INC{'Cpanel/Plugins/Components/Rules.pm'}             = 1;
    $INC{'Cpanel/Plugins/Components/Rules/Util/NVData.pm'} = 1;
    $INC{'Cpanel/Plugins/Components/Rules/CompanyId.pm'}   = 1;

    # Pre-load Cpanel modules
    $INC{'Cpanel/Server/Type.pm'} = 1;

    package Cpanel::Server::Type;
    sub get_products { return { 'cometbackup' => 1 }; }

    $INC{'Cpanel/PwCache.pm'} = 1;

    package Cpanel::PwCache;
    sub new { return bless {}, shift; }

    $INC{'Cpanel/Config/Users.pm'} = 1;

    package Cpanel::Config::Users;
    sub getcpusers { return qw(user1 user2); }

    # Pre-load CometBackup modules with stubs
    $INC{'Whostmgr/CometBackup/Setup.pm'} = 1;

    package Whostmgr::CometBackup::Setup;
    our @EXPORT = qw(is_comet_agent_installed is_agent_logged_in setup_comet_agent install_comet_agent);
    sub is_comet_agent_installed { return 0; }
    sub is_agent_logged_in       { return 0; }
    sub setup_comet_agent        { return 1; }
    sub install_comet_agent      { return 1; }

    $INC{'Whostmgr/CometBackup/AgentManager.pm'} = 1;

    package Whostmgr::CometBackup::AgentManager;
    our @EXPORT = qw(get_status start);
    sub get_status { return ( 1, 'active' ); }
    sub start      { return ( 1, '' ); }

    $INC{'Whostmgr/CometBackup/CometBackupAPI.pm'} = 1;

    package Whostmgr::CometBackup::CometBackupAPI;
    our @EXPORT = qw(get_server_config);
    sub get_server_config { return {}; }

    $INC{'Whostmgr/CometBackup/BackupRunLogs.pm'} = 1;

    package Whostmgr::CometBackup::BackupRunLogs;
    sub new             { return bless {}, shift; }
    sub get_recent_runs { return (); }

    # Mock BackupJobs module - CometBackup.pm loads this at compile time
    $INC{'Whostmgr/CometBackup/BackupJobs.pm'} = 1;

    package Whostmgr::CometBackup::BackupJobs;
    sub new                 { return bless {}, shift; }
    sub sanitize_text_input { return $_[0]; }
}

# Mock the Constants module BEFORE importing CometBackup
BEGIN {
    $INC{'Whostmgr/CometBackup/Constants.pm'} = 1;

    package Whostmgr::CometBackup::Constants;
    our $DISABLED_TOUCHFILE = '/var/cpanel/comet/comet_backup_disabled';
    our $BACKUP_RUNNER_PATH = '/usr/local/cpanel/backup-runner.pl';
    our $RUN_LOG_DB         = '/var/cpanel/comet/backup_run_logs.db';
    1;
}

use Whostmgr::API::1::CometBackup ();

# Mock the logger globally to prevent file access
my $mock_logger_global = Test::MockModule->new('Cpanel::Logger');
$mock_logger_global->redefine(
    'info'  => sub { return 1; },
    'error' => sub { return 1; },
    'warn'  => sub { return 1; },
    'debug' => sub { return 1; }
);

subtest 'register_server_with_comet_backup - server already configured' => sub {
    my $mock_utils = Test::MockModule->new('Whostmgr::API::1::Utils');
    $mock_utils->redefine(
        'set_metadata_ok' => sub {
            my ($metadata) = @_;
            $metadata->{ok} = 1;
            return 1;
        }
    );

    my $mock_cb = Test::MockModule->new('Whostmgr::API::1::CometBackup');
    $mock_cb->redefine(
        'get_comet_backup_configuration_status' => sub {
            return {
                configuration => {
                    status          => 'configured',
                    has_license     => 1,
                    agent_installed => 1,
                    agent_running   => 1,
                    has_credentials => 1,
                    agent_logged_in => 1,
                }
            };
        }
    );

    my $args     = {};
    my $metadata = {};

    my $response = Whostmgr::API::1::CometBackup::register_server_with_comet_backup( $args, $metadata );

    is $response, hash {
        field server => hash {
            field status => 'registered';
            end();
        };
        end();
    }, 'Returns status=registered when already configured';

    is $metadata->{ok}, 1, 'Metadata is set to ok';

    return;
};

subtest 'register_server_with_comet_backup - missing license' => sub {
    my $mock_utils = Test::MockModule->new('Whostmgr::API::1::Utils');
    $mock_utils->redefine(
        'set_metadata_not_ok' => sub {
            my ( $metadata, $error ) = @_;
            $metadata->{ok}    = 0;
            $metadata->{error} = $error;
            return 1;
        }
    );

    my $mock_cb = Test::MockModule->new('Whostmgr::API::1::CometBackup');
    $mock_cb->redefine(
        'get_comet_backup_configuration_status' => sub {
            return {
                configuration => {
                    status          => 'unlicensed',
                    has_license     => 0,
                    agent_installed => 0,
                    agent_running   => 0,
                    has_credentials => 0,
                    agent_logged_in => 0,
                }
            };
        }
    );

    my $args     = {};
    my $metadata = {};

    my $response = Whostmgr::API::1::CometBackup::register_server_with_comet_backup( $args, $metadata );

    is $response, hash {
        field server => 'unlicensed';
        end();
    }, 'Returns unlicensed status when license is missing';

    is $metadata->{ok}, 0, 'Metadata is set to not ok when license missing';
    like $metadata->{error}, qr/Failed to register server/, 'Error message indicates failure';

    return;
};

subtest 'register_server_with_comet_backup - agent installation' => sub {
    my $mock_utils = Test::MockModule->new('Whostmgr::API::1::Utils');
    $mock_utils->redefine(
        'set_metadata_ok' => sub {
            my ($metadata) = @_;
            $metadata->{ok} = 1;
            return 1;
        }
    );

    my $setup_called       = 0;
    my $agent_start_called = 0;

    my $mock_setup = Test::MockModule->new('Whostmgr::CometBackup::Setup');
    $mock_setup->redefine(
        'install_comet_agent' => sub {
            $setup_called = 1;
            return 1;
        },
        'setup_comet_agent' => sub {
            return 1;
        }
    );

    my $mock_agent = Test::MockModule->new('Whostmgr::CometBackup::AgentManager');
    $mock_agent->redefine(
        'start' => sub {
            $agent_start_called = 1;
            return ( 1, 'Agent started' );
        }
    );

    my $mock_cb = Test::MockModule->new('Whostmgr::API::1::CometBackup');
    $mock_cb->redefine(
        'get_comet_backup_configuration_status' => sub {
            return {
                configuration => {
                    status          => 'agent_not_installed',
                    has_license     => 1,
                    agent_installed => 0,
                    agent_running   => 0,
                    has_credentials => 1,
                    agent_logged_in => 0,
                }
            };
        }
    );

    my $args     = {};
    my $metadata = {};

    my $response = Whostmgr::API::1::CometBackup::register_server_with_comet_backup( $args, $metadata );

    is $response, hash {
        field server => hash {
            field status => 'registered';
            end();
        };
        end();
    }, 'Returns registered status after agent installation';

    is $metadata->{ok}, 1, 'Metadata is set to ok after installation';

    return;
};

subtest 'register_server_with_comet_backup - agent start failure' => sub {
    my $mock_utils = Test::MockModule->new('Whostmgr::API::1::Utils');
    $mock_utils->redefine(
        'set_metadata_not_ok' => sub {
            my ( $metadata, $error ) = @_;
            $metadata->{ok}    = 0;
            $metadata->{error} = $error;
            return 1;
        }
    );

    my $mock_setup = Test::MockModule->new('Whostmgr::CometBackup::Setup');
    $mock_setup->redefine(
        'install_comet_agent' => sub {
            return 1;
        }
    );

    my $mock_agent = Test::MockModule->new('Whostmgr::CometBackup::AgentManager');
    $mock_agent->redefine(
        'start' => sub {
            return ( 0, 'Agent failed to start' );
        }
    );

    my $mock_cb = Test::MockModule->new('Whostmgr::API::1::CometBackup');
    $mock_cb->redefine(
        'get_comet_backup_configuration_status' => sub {
            return {
                configuration => {
                    status          => 'agent_installed',
                    has_license     => 1,
                    agent_installed => 1,
                    agent_running   => 0,
                    has_credentials => 1,
                    agent_logged_in => 0,
                }
            };
        }
    );

    my $args     = {};
    my $metadata = {};

    my $response = Whostmgr::API::1::CometBackup::register_server_with_comet_backup( $args, $metadata );

    is $response, hash {
        field server => undef;
        end();
    }, 'Returns undef server when agent start fails';

    is $metadata->{ok}, 0, 'Metadata is set to not ok when agent start fails';

    return;
};

subtest 'register_server_with_comet_backup - missing credentials' => sub {
    my $mock_utils = Test::MockModule->new('Whostmgr::API::1::Utils');
    $mock_utils->redefine(
        'set_metadata_not_ok' => sub {
            my ( $metadata, $error ) = @_;
            $metadata->{ok}    = 0;
            $metadata->{error} = $error;
            return 1;
        }
    );

    my $mock_setup = Test::MockModule->new('Whostmgr::CometBackup::Setup');
    $mock_setup->redefine(
        'install_comet_agent' => sub {
            return 1;
        }
    );

    my $mock_agent = Test::MockModule->new('Whostmgr::CometBackup::AgentManager');
    $mock_agent->redefine(
        'start' => sub {
            return ( 1, 'Agent started' );
        }
    );

    my $mock_cb = Test::MockModule->new('Whostmgr::API::1::CometBackup');
    $mock_cb->redefine(
        'get_comet_backup_configuration_status' => sub {
            return {
                configuration => {
                    status          => 'credentials_missing',
                    has_license     => 1,
                    agent_installed => 1,
                    agent_running   => 1,
                    has_credentials => 0,
                    agent_logged_in => 0,
                }
            };
        }
    );

    my $args     = {};
    my $metadata = {};

    my $response = Whostmgr::API::1::CometBackup::register_server_with_comet_backup( $args, $metadata );

    is $response, hash {
        field server => 'credentials_missing';
        end();
    }, 'Returns credentials_missing status when credentials are missing';

    is $metadata->{ok}, 0, 'Metadata is set to not ok when credentials missing';
    like $metadata->{error}, qr/Failed to register server/, 'Error message indicates failure';

    return;
};

subtest 'register_server_with_comet_backup - complete success path' => sub {
    my $mock_utils = Test::MockModule->new('Whostmgr::API::1::Utils');
    $mock_utils->redefine(
        'set_metadata_ok' => sub {
            my ($metadata) = @_;
            $metadata->{ok} = 1;
            return 1;
        }
    );

    my $setup_agent_called = 0;

    my $mock_setup = Test::MockModule->new('Whostmgr::CometBackup::Setup');
    $mock_setup->redefine(
        'setup_comet_agent' => sub {
            $setup_agent_called = 1;
            return 1;
        }
    );

    my $mock_cb = Test::MockModule->new('Whostmgr::API::1::CometBackup');
    $mock_cb->redefine(
        'get_comet_backup_configuration_status' => sub {
            return {
                configuration => {
                    status          => 'agent_not_logged_in',
                    has_license     => 1,
                    agent_installed => 1,
                    agent_running   => 1,
                    has_credentials => 1,
                    agent_logged_in => 0,
                }
            };
        }
    );

    my $args     = {};
    my $metadata = {};

    my $response = Whostmgr::API::1::CometBackup::register_server_with_comet_backup( $args, $metadata );

    is $response, hash {
        field server => hash {
            field status => 'registered';
            end();
        };
        end();
    }, 'Returns registered status on successful registration';

    is $metadata->{ok}, 1, 'Metadata is set to ok on successful registration';

    return;
};

done_testing();
