#!/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 => 'Cpanel::Sitejet::Beta::Setup';
use Capture::Tiny;

use Cpanel::Sitejet::Beta::Setup;

my $root_path = '/var/cpanel/feature-flags';

no warnings 'once';
*Cpanel::Autodie::sysopen          = *CORE::GLOBAL::sysopen;
*Cpanel::Autodie::unlink_if_exists = *CORE::GLOBAL::unlink;

my @flag_names = (
    'cpanel.sitejet-beta.plugin.local.disable',
    'cpanel.sitejet-beta.plugin.local.enable',
);

sub mock_files( $create = {} ) {
    my @mocks;
    foreach my $flag_name (@flag_names) {
        my $flag_path  = "$root_path/$flag_name";
        my $touch_file = $create->{$flag_name} // 0;
        push @mocks, Test::MockFile->file( $flag_path, $touch_file ? "" : undef );
    }
    return @mocks;
}

subtest 'local_enable' => sub {
    my @mocks = mock_files();

    Cpanel::Sitejet::Beta::Setup::local_enable();

    my $flag_path = "$root_path/cpanel.sitejet-beta.plugin.local.enable";
    ok -e $flag_path, "Flag file '$flag_path' created successfully";
};

subtest 'local_disable' => sub {
    my @mocks = mock_files();

    Cpanel::Sitejet::Beta::Setup::local_disable();

    my $flag_path = "$root_path/cpanel.sitejet-beta.plugin.local.disable";
    ok -e $flag_path, "Flag file '$flag_path' created successfully";
};

subtest 'local_reset' => sub {
    my @mocks = mock_files(

        # Create both files to ensure they are removed.
        {
            'cpanel.sitejet-beta.plugin.local.disable' => 1,
            'cpanel.sitejet-beta.plugin.local.enable'  => 1,
        }
    );

    Cpanel::Sitejet::Beta::Setup::local_reset();

    foreach my $flag_name (@flag_names) {
        my $flag_path = "$root_path/$flag_name";
        ok !-e $flag_path, "Flag file '$flag_path' removed successfully.";
    }
};

done_testing;
