package Cpanel::Koality::ApiClient;

# cpanel - Cpanel/Koality/ApiClient.pm             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

use Moo;
use cPstrict;
extends 'Cpanel::Plugins::RestApiClient';

use Cpanel::Koality::Auth ();

=head1 MODULE

C<Cpanel::Koality::ApiClient>

=head1 DESCRIPTION

C<Cpanel::Koality::ApiClient> is a subclass of Cpanel::Plugins::RestApiClient
for use with Koality Site Quality Monitoring.

=head1 METHODS

=head2 new( cpanel_username )

Instantiate a C<Cpanel::Koality::ApiClient> object.

=head3 ARGUMENTS

=over

=item cpanel_username - string - Required

The user's cPanel username.

=back

=head3 RETURNS

A C<Cpanel::Koality::ApiClient> object.

=head3 EXAMPLES

my $api = Cpanel::Koality::ApiClient->new( cpanel_username => 'the_username' );

$api->method('GET');

$api->endpoint( "project/systems/id/systemType" );

$api->payload( { access_token => 'a_token' } );

my $response = $api->run();

=head2 reauth_handler()

Reauthenticates the Koality session and updates the authentication token used
by the C<Cpanel::Koality::ApiClient> object.

=head3 ARGUMENTS

None.

=head3 RETURNS

Returns 1.

=head3 EXAMPLES

my $api = Cpanel::Koality::ApiClient->new( cpanel_username => 'the_username' );

$api->reauth_handler();

=cut

has 'cpanel_username' => (
    is  => 'rw',
    isa => sub {
        require Cpanel::Validate::Username;
        Cpanel::Validate::Username::user_exists_or_die( $_[0] );
    },
    default => sub ($self) { return $Cpanel::user || die 'Must set the cpanel_username attribute.' }
);

sub reauth_handler ($self) {
    $Cpanel::user //= $self->cpanel_username;

    my $auth = Cpanel::Koality::Auth->new( 'cpanel_username' => $self->cpanel_username );

    # Only reauth to an api cluster endpoint.
    return 0 unless defined $self->base_url;
    return 0 if $self->base_url eq $auth->auth_url || $self->base_url eq $auth->app360_url;

    # disable trying to reauth our reauth.
    $auth->api->try_reauth('0');
    my $user = $auth->auth_session();

    $self->auth_token( $user->session_token );
    $self->payload->{access_token} = $user->session_token;

    return 1;
}

1;
