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

# cpanel - t/medium/Cpanel-API-Plugins.t       Copyright 2024 cPanel, L.L.C.
#                                                           All rights reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited

package t::medium::Cpanel::API::Plugins;

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 Cpanel::Args   ();
use Cpanel::Result ();

use Cpanel::API::Plugins ();

use base qw(Test::Class);

my $mock_privs = Test::MockModule->new('Cpanel::AccessIds::ReducedPrivileges');
$mock_privs->redefine( 'new' => sub { return 1 } );

my $mock_val_username = Test::MockModule->new('Cpanel::Validate::Username');
$mock_val_username->redefine( 'user_exists_or_die' => sub { return 1 } );

my $mock_val_uuid = Test::MockModule->new('Cpanel::Validate::UUID');
$mock_val_uuid->redefine( 'validate_uuid_or_die' => sub { return 1 } );

my $mock_uuid_good = '7bde24ae-d42d-4d50-bd85-9e3d733424c1';
my $mock_uuid;

my $mock_uuid_gen = Test::MockModule->new('Cpanel::UUID');
$mock_uuid_gen->redefine( 'random_uuid' => sub { return $mock_uuid } );

my $homedir      = File::Temp->newdir();
my $mock_pwcache = Test::MockModule->new('Cpanel::PwCache');
$mock_pwcache->redefine( 'gethomedir' => sub { return $homedir } );

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

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

sub _test_setup : Tests(setup) {

    $Cpanel::user = 'human';
    unlink "$homedir/.cpanel/plugin_uuid";
    unlink "$homedir/.cpanel";
    $mock_uuid = $mock_uuid_good;

    return;
}

sub test_get_uuid : Tests(2) {

    my $args;
    my $result = Cpanel::Result->new();

    $args = Cpanel::Args->new();
    ok( lives { Cpanel::API::Plugins::get_uuid( $args, $result ) }, "get_uuid call lives." );
    is( $result->data->{uuid}, '7bde24ae-d42d-4d50-bd85-9e3d733424c1', "Got expected result for uuid." );

    return 1;
}

sub test_reset_uuid : Tests(3) {

    my $result = Cpanel::Result->new();
    my $args   = Cpanel::Args->new();

    ok( lives { Cpanel::API::Plugins::get_uuid( $args, $result ) }, "get_uuid call lives." );
    my $old_uuid = $result->data->{uuid};

    $mock_uuid = '22222222-2222-2222-2222-222222222222';
    ok( lives { Cpanel::API::Plugins::reset_uuid( $args, $result ) }, "reset_uuid call lives." );

    isnt( $result->data->{uuid}, $old_uuid, "New uuid doesn't match old uuid." );

    return 1;
}

1;
