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

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

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

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

use Cpanel::Koality::Base ();

use base qw(Test::Class);

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

my $mock_serverid = Test::MockModule->new('Cpanel::Plugins::ServerId');
$mock_serverid->redefine( 'get_server_id' => sub { return '101010101' } );

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

sub test_constructor : Tests(7) {

    my $mock_stage_file = Test::MockFile->file('/var/cpanel/use_koality_stage');

    my $mock_validate = Test::MockModule->new('Cpanel::Koality::Validate');
    $mock_validate->redefine( 'valid_api_object' => sub { return 1 } );

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

    my $mock_api = Test::MockModule->new('Cpanel::Koality::ApiClient');
    $mock_api->redefine( 'new' => sub { return bless {}, shift } );

    my $mock_locale = Test::MockModule->new('Cpanel::Locale::Utils::User');
    $mock_locale->redefine( 'get_user_locale' => sub { return 'en' } );

    my $mock_companyid = Test::MockModule->new('Cpanel::License::CompanyID');
    $mock_companyid->redefine( 'get_company_id' => sub { return '42' } );

    my $mock_serverid = Test::MockModule->new('Cpanel::Plugins::ServerId');
    $mock_serverid->redefine( 'get_server_id' => sub { return '101010' } );

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

    my $obj = Cpanel::Koality::Base->new();
    is( $obj->cpanel_username, $expected_user, "Got correct user set with Cpanel::user." );

    is( $obj->use_stage, 0, "Got correct use stage value when not using stage." );

    $mock_stage_file->touch();
    $obj = Cpanel::Koality::Base->new();
    is( $obj->use_stage, 1, "Got correct use stage value when using stage." );

    is( $obj->company_id, 42, "Got the expected company id" );

    ok( $obj->api->isa('Cpanel::Koality::ApiClient'), "API obj is of the correct class." );

    like(
        dies { Cpanel::Koality::Base->new( company_id => undef ); },
        qr/company_id is not defined/,
        "Dies if the company id is undefined",
    );

    like(
        dies { Cpanel::Koality::Base->new( server_id => undef ); },
        qr/server_id is not defined/,
        "Dies if the server id is undefined",
    );

    return;
}

1;
