
#                                      Copyright 2024 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 Whostmgr::360Monitoring::ApiClient;

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

use Whostmgr::360Monitoring::Auth ();

=head1 MODULE

C<Whostmgr::360Monitoring::ApiClient>

=head1 DESCRIPTION

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

=head1 METHODS

=head2 new( username )

Instantiate a C<Whostmgr::360Monitoring::ApiClient> object.

=head3 ARGUMENTS

=over

=item username - string - Required

The user's cPanel username.

=back

=head3 RETURNS

A C<Whostmgr::360Monitoring::ApiClient> object.

=head3 EXAMPLES

my $api = Whostmgr::360Monitoring::ApiClient->new( 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 360Monitoring session and updates the authentication token used
by the C<Whostmgr::360Monitoring::ApiClient> object.

=head3 ARGUMENTS

None.

=head3 RETURNS

Returns 1.

=head3 EXAMPLES

my $api = Whostmgr::360Monitoring::ApiClient->new( username => 'the_username' );

$api->reauth_handler();

=cut

has '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 username attribute.' }
);

sub reauth_handler ($self) {
    $Cpanel::user = $self->username if !$Cpanel::user;

    my $auth = Cpanel::360Monitoring::Auth->new( 'username' => $self->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;
