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

# cpanel - t/medium/Cpanel-Admin-Modules-Cpanel-xovi.t
#                                     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 t::medium::Cpanel::Admin::Modules::Cpanel::xovi;

use Test2::V0 -no_utf8 => 1;
use Test2::Tools::Explain;
use Test2::Plugin::NoWarnings;
use Test2::Tools::Exception qw/dies/;

use Test::MockObject;
use Test::MockFile;
use Test::MockTime;
use Test::Warn;

use Try::Tiny;

use Test::Cpanel::Policy;

use parent qw(
  Cpanel::TestObj
);

use Cpanel::Admin::Modules::Cpanel::xovi ();

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

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

#e.g., num_method_tests()
sub new ( $class, @args ) {
    my $self = $class->SUPER::new(@args);
    return $self;
}

#e.g., set environs before running tests
sub runtests ( $self, @args ) {
    $self->{'mock_cpuser_file_DNE'} = Test::MockFile->file('/var/cpanel/users/team_user_name');
    return $self->SUPER::runtests(@args);
}

sub test_CREATE_USER : Tests(8) ($self) {
    my $file              = '/var/cpanel/plugins/xovi/.config/secrets';
    my $expected_endpoint = '.third-party-users';
    my $expected_method   = 'PUT';
    my $expected_baseurl  = 'https://api.xovi.net/';
    my $expcted_payload = {
        'data' => {
            'auth-method'      => { 'data-type' => 'Xovi\\API\\Auth\\Method\\XoviApikey' },
            'third-party-data' => [
                {
                    'data' => {
                        'label' => 'company_id',
                        'value' => 7
                    },
                    'data-type' => 'Xovi\\API\\Data\\Types\\User\\ThirdPartyData'
                },
                {
                    'data-type' => 'Xovi\\API\\Data\\Types\\User\\ThirdPartyData',
                    'data'      => {
                        'label' => 'panel_username',
                        'value' => 'cpuser'
                    }
                },
                {
                    'data-type' => 'Xovi\\API\\Data\\Types\\User\\ThirdPartyData',
                    'data'      => {
                        'label' => 'server_id',
                        'value' => '12ghhbjhakjkj-10.11.11.11'
                    }
                },
            ]
        },
        'meta'      => { 'verification' => { 'data-type' => 'Xovi\\API\\Data\\Meta\\Verification\\CpanelExtension' } },
        'data-type' => 'Xovi\\API\\Auth\\SecurityConstraints'
    };
    my $expected_header = {
        'user-agent'       => 'libwww-perl/6.67',
        'Xoviapi-Key'      => '1bnbjh123jh12',
        'Content-Type'     => 'application/json',
        'Xoviapi-Password' => 'hjh12324jhkjaqb'
    };
    my @file_mocks;

    my ( $got_endpoint, $got_payload, $got_baseurl, $got_method, $got_header );
    my $contents = <<secrets_to_contents;
username:1bnbjh123jh12
credential:hjh12324jhkjaqb
secrets_to_contents
    push @file_mocks, Test::MockFile->file( $file, $contents );
    my $response =
      '{"status":{"name":"READY"},"data-type":"Xovi\\\\API\\\\Data\\\\Types\\\\User\\\\ThirdPartyUser","data":{"security":{"data-type":"Xovi\\\\API\\\\Auth\\\\SecurityConstraints","data":{"auth-method":{"data-type":"Xovi\\\\API\\\\Auth\\\\Method\\\\XoviApikey","data":[]}},"meta":{"verification":{"data-type":"Xovi\\\\API\\\\Data\\\\Meta\\\\Verification\\\\CpanelExtension","data":{"address":"184.94.197.2"}}}},"apikey":"2b9dffb1e614031eb5788d21a1a"}}';
    my @mocks = (
        $self->mock_subs(
            'Cpanel::Plugins::RestApiClient::run' => sub {
                my $self = shift;
                $got_endpoint = $self->endpoint;
                $got_payload  = $self->payload;
                $got_baseurl  = $self->base_url;
                $got_method   = $self->method;
                $got_header   = $self->headers;
                return $response;
            },
            'Cpanel::Admin::Base::get_caller_username'   => 'cpuser',
            'Cpanel::License::CompanyID::get_company_id' => 7,
            'Cpanel::Plugins::ServerId::get_server_id'   => '12ghhbjhakjkj-10.11.11.11',
        )
    );
    my $got = Cpanel::Admin::Modules::Cpanel::xovi->CREATE_USER();

    is( $got,          '2b9dffb1e614031eb5788d21a1a', 'CREATE_USER runs without errors and gets the API key' ) or explain $got;
    is( $got_endpoint, $expected_endpoint,            'CREATE_USER gets the expected endpoint' )               or explain $got_endpoint;
    is( $got_payload,  $expcted_payload,              'CREATE_USER gets the expected payload' )                or explain $got_payload;
    is( $got_baseurl,  $expected_baseurl,             'CREATE_USER gets the expected endpoint' )               or explain $got_baseurl;
    is( $got_method,   $expected_method,              'CREATE_USER gets the expected method' )                 or explain $got_method;
    is( $got_header,   $expected_header,              'CREATE_USER gets the expected header' )                 or explain $got_header;

    # handle failure when token is not valid
    @file_mocks = '';
    push @file_mocks, Test::MockFile->file( $file, '' );

    @mocks = ();
    @mocks = (
        $self->mock_subs(
            'Cpanel::Plugins::RestApiClient::run' => sub {
                my $self = shift;
                $got_endpoint = $self->endpoint;
                $got_payload  = $self->payload;
                $got_baseurl  = $self->base_url;
                $got_method   = $self->method;
                $got_header   = $self->headers;
                die("The response to the request indicated an error (403, Forbidden):") if !$got_header->{'Xoviapi-Key'} || !$got_header->{'Xoviapi-Password'};
            },
            'Cpanel::Admin::Base::get_caller_username'   => 'cpuser',
            'Cpanel::License::CompanyID::get_company_id' => 7,
            'Cpanel::Plugins::ServerId::get_server_id'   => '12ghhbjhakjkj-10.11.11.11',
        )
    );

    like(
        dies {
            $got = Cpanel::Admin::Modules::Cpanel::xovi->CREATE_USER();
        },
        qr/The response to the request indicated an error \(403\, Forbidden/,
        "CREATE_USER dies as expected when we do not have the right header"
    );

    # handle failure when token file not available
    @file_mocks = '';
    push @file_mocks, Test::MockFile->file($file);

    like(
        dies {
            $got = Cpanel::Admin::Modules::Cpanel::xovi->CREATE_USER();
        },
        qr/The system could not read the tokens file/,
        "CREATE_USER dies as expected when we are unable to read token."
    );

    return;
}
