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

#                                      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.

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

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

use Test::MockModule;
use Test::MockFile;
use Cpanel::JSON;

BEGIN {
    $INC{'Cpanel/Plugins/Components/Rules.pm'}             = 1;
    $INC{'Cpanel/Plugins/Components/Rules/Util/NVData.pm'} = 1;
    $INC{'Cpanel/Plugins/Components/Rules/CompanyId.pm'}   = 1;

    $INC{'Cpanel/Server/Type.pm'} = 1;
    package Cpanel::Server::Type;
    sub get_products { return { 'cometbackup' => 1 }; }

    $INC{'Cpanel/PwCache.pm'} = 1;
    package Cpanel::PwCache;
    sub new { return bless {}, shift; }

    $INC{'Cpanel/Config/Users.pm'} = 1;
    package Cpanel::Config::Users;
    sub getcpusers { return qw(user1 user2); }

    $INC{'Whostmgr/CometBackup/Setup.pm'} = 1;
    package Whostmgr::CometBackup::Setup;
    our @EXPORT = qw(is_comet_agent_installed is_agent_logged_in setup_comet_agent install_comet_agent);
    sub is_comet_agent_installed { return 0; }
    sub is_agent_logged_in       { return 0; }
    sub setup_comet_agent        { return 1; }
    sub install_comet_agent      { return 1; }

    $INC{'Whostmgr/CometBackup/AgentManager.pm'} = 1;
    package Whostmgr::CometBackup::AgentManager;
    our @EXPORT = qw(get_status start);
    sub get_status { return ( 1, 'active' ); }
    sub start      { return ( 1, '' ); }

    $INC{'Whostmgr/CometBackup/CometBackupAPI.pm'} = 1;
    package Whostmgr::CometBackup::CometBackupAPI;
    sub new  { return bless {}, shift; }
    sub call { return {}; }
    sub make_server_request { return {}; }

    $INC{'Whostmgr/CometBackup/Constants.pm'} = 1;
    package Whostmgr::CometBackup::Constants;
    sub get_text_log_file_path { return '/var/log/comet.log'; }

    $INC{'Whostmgr/API/1/Utils.pm'} = 1;
    package Whostmgr::API::1::Utils;
    sub set_metadata_ok    { $_[0]->{result} = 1; }
    sub set_metadata_not_ok { $_[0]->{result} = 0; }

    $INC{'Cpanel/Mkdir.pm'} = 1;
    package Cpanel::Mkdir;
    sub ensure_directory_existence_and_mode { return 1; }

    $INC{'Data/UUID.pm'} = 1;
    package Data::UUID;
    sub new { return bless {}, shift; }
    sub create_str { return '550e8400-e29b-41d4-a716-446655440000'; }
}

use Whostmgr::API::1::CometBackup ();

my @mock_files = (
    Test::MockFile->file('/usr/local/cpanel/logs/error_log'),
    Test::MockFile->dir('/backup'),
    Test::MockFile->file('/var/cpanel/server_locale'),
);

subtest 'create_local_storage - missing JSON parameter' => sub {
    my $metadata = {};
    my $args     = {};

    my $result = Whostmgr::API::1::CometBackup::create_local_storage( $args, $metadata );

    is( $metadata->{result}, 0, 'Metadata result is not ok' );
    ok( !defined $result, 'Result is undef when JSON parameter missing' );
};

subtest 'create_local_storage - missing local_path' => sub {
    my $metadata = {};
    my $args     = { json => Cpanel::JSON::Dump( { name => 'Test Storage' } ) };

    my $result = Whostmgr::API::1::CometBackup::create_local_storage( $args, $metadata );

    is( $metadata->{result}, 0, 'Metadata result is not ok' );
    is( $result->{created}, 0, 'Created is 0' );
};

subtest 'create_local_storage - missing name' => sub {
    my $metadata = {};
    my $args     = { json => Cpanel::JSON::Dump( { local_path => '/backup' } ) };

    my $result = Whostmgr::API::1::CometBackup::create_local_storage( $args, $metadata );

    is( $metadata->{result}, 0, 'Metadata result is not ok' );
    is( $result->{created}, 0, 'Created is 0' );
};

subtest 'create_local_storage - successful creation' => sub {
    my $mock_api = Test::MockModule->new('Whostmgr::CometBackup::CometBackupAPI');
    $mock_api->redefine( 'make_server_request' => sub {
        my ( $action, $data ) = @_;
        
        if ( $action eq 'user/web/get-user-profile-and-hash' ) {
            return {
                Status      => 200,
                ProfileHash => 'hash123',
                Profile     => { Destinations => {} }
            };
        }
        elsif ( $action eq 'user/web/set-profile-hash' ) {
            return { Status => 200 };
        }
        return { Status => 500 };
    } );

    my $metadata = {};
    my $args     = { json => Cpanel::JSON::Dump( { 
        local_path  => '/backup',
        name        => 'Backup Storage',
        description => 'My backup location'
    } ) };

    my $result = Whostmgr::API::1::CometBackup::create_local_storage( $args, $metadata );

    is( $metadata->{result}, 1, 'Metadata result is ok' );
    is( $result->{created}, 1, 'Created is 1' );
    ok( defined $result->{destination_id}, 'Destination ID is defined' );
};

subtest 'create_local_storage - get profile fails' => sub {
    my $mock_api = Test::MockModule->new('Whostmgr::CometBackup::CometBackupAPI');
    $mock_api->redefine( 'make_server_request' => sub {
        return { Status => 500, Message => 'Server error' };
    } );

    my $metadata = {};
    my $args     = { json => Cpanel::JSON::Dump( { 
        local_path => '/backup',
        name       => 'Backup Storage'
    } ) };

    my $result = Whostmgr::API::1::CometBackup::create_local_storage( $args, $metadata );

    is( $metadata->{result}, 0, 'Metadata result is not ok' );
    is( $result->{created}, 0, 'Created is 0' );
};

subtest 'create_local_storage - set profile fails' => sub {
    my $mock_api = Test::MockModule->new('Whostmgr::CometBackup::CometBackupAPI');
    my $call_count = 0;
    $mock_api->redefine( 'make_server_request' => sub {
        my ( $action, $data ) = @_;
        $call_count++;
        
        if ( $call_count == 1 ) {
            return {
                Status      => 200,
                ProfileHash => 'hash123',
                Profile     => { Destinations => {} }
            };
        }
        return { Status => 500, Message => 'Failed to update' };
    } );

    my $metadata = {};
    my $args     = { json => Cpanel::JSON::Dump( { 
        local_path => '/backup',
        name       => 'Backup Storage'
    } ) };

    my $result = Whostmgr::API::1::CometBackup::create_local_storage( $args, $metadata );

    is( $metadata->{result}, 0, 'Metadata result is not ok' );
    is( $result->{created}, 0, 'Created is 0' );
};

subtest 'create_local_storage - description defaults to name' => sub {
    my $mock_api = Test::MockModule->new('Whostmgr::CometBackup::CometBackupAPI');
    my $profile_data;
    $mock_api->redefine( 'make_server_request' => sub {
        my ( $action, $data ) = @_;
        
        if ( $action eq 'user/web/get-user-profile-and-hash' ) {
            return {
                Status      => 200,
                ProfileHash => 'hash123',
                Profile     => { Destinations => {} }
            };
        }
        elsif ( $action eq 'user/web/set-profile-hash' ) {
            $profile_data = Cpanel::JSON::Load( $data->{ProfileData} );
            return { Status => 200 };
        }
        return { Status => 500 };
    } );

    my $metadata = {};
    my $args     = { json => Cpanel::JSON::Dump( { 
        local_path => '/backup',
        name       => 'My Storage'
    } ) };

    my $result = Whostmgr::API::1::CometBackup::create_local_storage( $args, $metadata );

    is( $metadata->{result}, 1, 'Metadata result is ok' );
    is( $result->{created}, 1, 'Created is 1' );
};

subtest 'create_local_storage - empty local_path string' => sub {
    my $metadata = {};
    my $args     = { json => Cpanel::JSON::Dump( { 
        local_path => '',
        name       => 'Test'
    } ) };

    my $result = Whostmgr::API::1::CometBackup::create_local_storage( $args, $metadata );

    is( $metadata->{result}, 0, 'Metadata result is not ok' );
    is( $result->{created}, 0, 'Created is 0' );
};

subtest 'create_local_storage - response structure' => sub {
    my $mock_api = Test::MockModule->new('Whostmgr::CometBackup::CometBackupAPI');
    $mock_api->redefine( 'make_server_request' => sub {
        my ( $action, $data ) = @_;
        
        if ( $action eq 'user/web/get-user-profile-and-hash' ) {
            return {
                Status      => 200,
                ProfileHash => 'hash123',
                Profile     => { Destinations => {} }
            };
        }
        elsif ( $action eq 'user/web/set-profile-hash' ) {
            return { Status => 200 };
        }
        return { Status => 500 };
    } );

    my $metadata = {};
    my $args     = { json => Cpanel::JSON::Dump( { 
        local_path => '/backup',
        name       => 'Test Storage'
    } ) };

    my $result = Whostmgr::API::1::CometBackup::create_local_storage( $args, $metadata );

    ok( exists $result->{created}, 'Response has created key' );
    ok( exists $result->{destination_id}, 'Response has destination_id key' );
};

done_testing();
