#!/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
package Cpanel::Plugins::Components::Rules::Util::Filter;
use cPstrict;

use Test2::V0;
use Test2::Tools::Explain;

use Cpanel::Plugins::Components::Rules::Util::Filter;

my $processed_rules = [
    {
        'or' => [
            'date-range' => {
                'start_date' => '08-10-2024',
                'end_date'   => '10-15-2024'
            },
            'company-id' => [7]
        ]
    },
    {
        'date-range' => {
            'start_date' => '08-10-2024',
            'end_date'   => '10-15-2024'
        },
    },
    { 'company-id' => [7] },
];

my $expected_output = {

    # and operator with complex or returns undef
    'case1' => undef,

    # or operator with complex or rule returns inner value of 'or'
    'case2' => {
        'date-range' => {
            'start_date' => '08-10-2024',
            'end_date'   => '10-15-2024'
        },
        'company-id' => [7]
    },

    # and operator with simple rule returns 'date-range'
    'case3' => {
        'date-range' => {
            'start_date' => '08-10-2024',
            'end_date'   => '10-15-2024'
        }
    },

    # or operator with simple rule returns 'date-range'
    'case4' => {
        'date-range' => {
            'start_date' => '08-10-2024',
            'end_date'   => '10-15-2024'
        }
    },

    # and operator with no 'date-range' returns as is which will be ignored in
    # find_date_range as it does not have 'date-range'
    'case5' => { 'company-id' => [7] },

    # or operator with no 'date-range' returns as is which will be ignored in
    # find_date_range as it does not have 'date-range'
    'case6' => { 'company-id' => [7] },
};

subtest 'Verify Find date range' => sub {
    my $output_rule;
    my $i = 0;
    foreach my $processed_rule ( @{$processed_rules} ) {
        foreach my $operator (qw/and or/) {
            $i++;
            $output_rule = Cpanel::Plugins::Components::Rules::Util::Filter::find_date_range( $processed_rule, $operator );
            my $case = "case$i";
            is $output_rule, $expected_output->{$case}, "find_date_range method returns expected output for $case.";
        }
    }
};

done_testing;
