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

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

package main;

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

use Test2::V0;
use Test2::Tools::Explain;
use Test2::Tools::Compare;
use Test2::Plugin::NoWarnings;
use Test2::Tools::Exception;
use Test::MockModule;
use Test::MockFile;

use Common::Plugins::Setup ();

use base qw(Test::Class);

__PACKAGE__->new()->runtests() if !caller;

#----------------------------------------------------------------------

sub test_run_from_module : Tests() {

    my %valid_expected_data = (
        'Whostmgr' => 'cpanel-monitoring-plugin',
    );
    my @valid_methods = ( 'enable', 'disable' );

    my @invalid_methods = ( 'abc', 'xyz' );

    # The require Whostmgr::360Monitoring::Setup fails
    # and i had to work around by mocking the method
    # which does the require
    my $mock_loadrun = Test::MockModule->new('Common::Plugins::LoadRun');
    $mock_loadrun->redefine( 'run_from_module' => 1 );

    no warnings 'once';
    local *Whostmgr::360Monitoring::Setup::local_enable  = sub { return 1 };
    local *Whostmgr::360Monitoring::Setup::local_disable = sub { return 1 };

    foreach my $app_name ( keys %valid_expected_data ) {
        my $plugin_name = $valid_expected_data{$app_name};
        foreach my $method (@valid_methods) {
            my $status = Common::Plugins::Setup::run_from_module( $app_name, $plugin_name, $method );
            is( $status, 1, "run_from_module runs as expected when passed with valid app_name $app_name plugin_name:$plugin_name method:$method" );
        }
        foreach my $method (@invalid_methods) {
            eval { Common::Plugins::Setup::run_from_module( $app_name, $plugin_name, $method ) };
            my $exception = $@;
            like( $exception, qr/The function $method is not allowed to run by API/, "run_from_module fails when passing invalid method name: $method" );
        }
    }

    # pass wrong plugin name or not implemented module
    eval { Common::Plugins::Setup::run_from_module( 'Whostmgr', 'non-existing-plugin', 'enable' ) };
    my $exception = $@;
    like( $exception, qr/The plugin non-existing-plugin was not found/, "run_from_module fails when providing non-existing plugins" );

    return 1;
}

1;
