package Cpanel::Plugins::Components::Rules::FeatureEnabled;
use cPstrict;

use Cpanel::Plugin::Install ();
use Cpanel::Features::Check ();

use Moo;
extends 'Cpanel::Plugins::Components::Rules::Base';

=head1 MODULE

C<Cpanel::Plugins::Components::Rules::FeatureEnabled>

=head1 DESCRIPTION

Use this rule to test if a specific cPanel feature is enabled.

Defaults to false.

=head1 SYNOPSIS

Using perl code:

  use Cpanel::Plugins::Components::Rules::FeatureEnabled;
  my $is_allowed = Cpanel::Plugins::Components::Rules::FeatureEnabled->new(
    'xovi'
  )->is_allowed();

Using the declaritive syntax:

  [
    "feature-enabled": "xovi"
  ]

=cut

around BUILDARGS => sub {
    my ( $orig, $class, @args ) = @_;

    # Check if its a string
    return { config =>  $args[0]  }
      if @args == 1 && !ref $args[0];

    return $class->$orig(@args);
};

=head1 METHODS

=over

=item * is_allowed -- Allow the campaign if rules are met.

    Check if the feature is enabled for the current user.

    RETURNS
        0 - The feature is disabled.
        1 - The feature is enabled.

    ERRORS
        Fails if the check_feature_for_user method fails.

=back

=cut

sub is_allowed ($self) {
    my $feature      = $self->config();
    my $feature_file = Cpanel::Plugin::Install::_addon_feature_directory() . '/' . $feature;
    return 0 if !-e $feature_file;
    my $is_enabled = Cpanel::Features::Check::check_feature_for_user( $Cpanel::user, $feature );
    return $is_enabled;
}

1;
