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

# cpanel - t/medium/Cpanel-Koality-ApiClient.t     Copyright 2023 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::Koality::ApiClient;

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

use Test2::V0;
use Test2::Plugin::NoWarnings;

use Cpanel::Koality::ApiClient ();

use base qw(Test::Class);

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

sub test_all : Tests(5) {

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

    my $expected_user = 'cpanel_user';
    $Cpanel::user = $expected_user;

    my $obj = Cpanel::Koality::ApiClient->new( http_client => 1, base_url => 'https://example.com' );
    is( $obj->cpanel_username, $expected_user, "Got correct user set with Cpanel::user." );

    ok( $obj->can('reauth_handler'), "Has a reauth handler." );

    my $mock_auth          = Test::MockModule->new('Cpanel::Koality::Auth');
    my $mock_no_verify_SSL = Test::MockFile->file( '/var/cpanel/no_verify_SSL', '' );
    $mock_auth->redefine( 'new'          => sub { return bless {}, 'Cpanel::Koality::Auth' } );
    $mock_auth->redefine( 'auth_session' => sub { return bless {}, 'Cpanel::Koality::Mock::User' } );
    $obj->payload( { access_token => 'abcd' } );

    ok( $obj->reauth_handler(), "reauth handler returns 1" );
    is( $obj->auth_token,              '1234', "Got updated auth_token." );
    is( $obj->payload->{access_token}, '1234', "Got updated access_token." );

    return;
}

1;

package Cpanel::Koality::Mock::User;

sub session_token { return '1234' }

1;
