#!/usr/local/cpanel/3rdparty/bin/perl -w
#                           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 Test2::V0;
use Test2::Tools::Explain;
use Test2::Plugin::NoWarnings;
use Test2::Tools::Subtest;
use Test2::Tools::Exception;

use Test::MockModule qw/strict/;
use Test::MockFile   qw/strict/;

use Test::Cpanel::Policy testing => 'Common::JSONC';

use Common::JSONC ();

subtest 'Test when file does not exist' => sub {
    my $mock = Test::MockFile->file('/tmp/test.jsonc');

    my $exception = dies { Common::JSONC::load_jsonc( '/tmp/test.jsonc', ) };

    like(
        $exception,
        qr/Cannot load file .* with error: .*/,
        "Got exception"
    );

    diag $exception;
};

subtest 'Test when file does not have valid JSONC' => sub {
    my $mock = Test::MockFile->file( '/tmp/test.jsonc', <<~ 'EOF');
    {
        "key": "value" /* Comment
    }
    EOF

    my $exception = dies { Common::JSONC::load_jsonc( '/tmp/test.jsonc', ) };
    like(
        $exception,
        qr/Cannot parse JSONC .* with error: .*/,
        "Got exception"
    );

    diag $exception;
};

subtest 'Test when file does not have valid JSON' => sub {
    my $mock = Test::MockFile->file( '/tmp/test.jsonc', <<~ 'EOF');
    {
        "key": "value
    }
    EOF

    my $exception = dies { Common::JSONC::load_jsonc( '/tmp/test.jsonc', ) };
    like(
        $exception,
        qr/Cannot parse JSONC .* with error: .*/,
        "Got exception"
    );

    diag $exception;
};

subtest 'Test loading a json file' => sub {
    my $mock = Test::MockFile->file( '/tmp/test.jsonc', <<~ 'EOF');
    {
        "key": "value"
    }
    EOF

    my $json = Common::JSONC::load_jsonc('/tmp/test.jsonc');
    is $json, { key => 'value' }, 'JSON loaded correctly';

    diag explain $json;
};

subtest 'Test loading a json file with // to end of line' => sub {
    my $mock = Test::MockFile->file( '/tmp/test.jsonc', <<~ 'EOF');
    {
        "key": "value" // Comment
    }
    EOF

    my $json = Common::JSONC::load_jsonc('/tmp/test.jsonc');
    is $json, { key => 'value' }, 'JSON loaded correctly';

    diag explain $json;
};

subtest 'Test loading a json file with /* */ terminators' => sub {
    my $mock = Test::MockFile->file( '/tmp/test.jsonc', <<~ 'EOF');
    {
        /* Comment */
        "key": "value"
    }
    EOF

    my $json = Common::JSONC::load_jsonc('/tmp/test.jsonc');
    is $json, { key => 'value' }, 'JSON loaded correctly';

    diag explain $json;
};

done_testing;
