
#                                      Copyright 2024 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 Whostmgr::360Monitoring::Types;

use strict;
use warnings;
use experimental 'builtin';
use builtin;
use Type::Library -base, -declare => qw(WPUrl WPUrlOrEmpty WPUrls WPBool WPStringArray);
use Types::Common     qw(Str Ref Str NonEmptyStr ArrayRef);
use Types::Serialiser ();
use feature 'signatures';

__PACKAGE__->add_type(
    name       => WPBool,
    constraint => \&Types::Serialiser::is_bool,
    coerce     => 1,
);

WPBool->coercion->add_type_coercions(
    Str, \&to_Bool,
    Ref, \&to_Bool
);

sub to_Bool ($val) {
    if ( ref $val eq 'SCALAR' ) {
        if    ( $$val == 1 ) { return Types::Serialiser::true }
        elsif ( $$val == 0 ) { return Types::Serialiser::false }
    }
    elsif ( $val eq 'yes' or $val eq 'true' ) {
        return Types::Serialiser::true;
    }
    elsif ( $val eq 'no' or $val eq 'false' ) {
        return Types::Serialiser::false;
    }
    elsif ( builtin::is_bool($val) ) {
        if ( $val == builtin::true ) {
            return Types::Serialiser::true;    # builtin::true();
        }
        else {
            return Types::Serialiser::false;    # builtin::false();
        }
    }
    else { return Types::Serialiser::as_bool($val) }
}

__PACKAGE__->add_type(
    name       => WPUrl,
    parent     => NonEmptyStr,
    constraint => sub ($value) {

        # TODO: Add a better URL validator
        die "$value is not a url" if $value !~ m{^http(s)?://};
        return 1;
    },
);

__PACKAGE__->add_type(
    name       => WPUrlOrEmpty,
    parent     => Str,
    constraint => sub ($value) {

        # TODO: Add a better URL validator
        return 1                  if !$value;
        die "$value is not a url" if $value !~ m{^http(s)?://};
        return 1;
    },
);

__PACKAGE__->add_type(
    name   => WPStringArray,
    parent => ArrayRef [NonEmptyStr],
    coerce => 1
);

__PACKAGE__->add_type(
    name   => WPUrls,
    parent => ArrayRef [WPUrl],
    coerce => 1
);

WPStringArray->coercion->add_type_coercions( Str, \&to_StringArray );

WPUrls->coercion->add_type_coercions( Str, \&to_StringArray );

sub to_StringArray ($str) {
    my @strings = split ',', $str;
    builtin::trim($_) for @strings;
    \@strings;
}

__PACKAGE__->make_immutable;
