package Cpanel::API::CCS;

# cpanel - Cpanel/API/CCS.pm                       Copyright 2020 cPanel, L.L.C.
#                                                           All rights reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited

use strict;
use warnings;

use Cpanel::AdminBin::Call ();

=encoding utf-8

=head1 MODULE

C<Cpanel::API::CCS>

=head1 DESCRIPTION

C<Cpanel::API::CCS> provides various API calls related to managing calendar &
contact data for your users .

=head1 FUNCTIONS

=cut

# NOTE -- not really testable in a unit test, so somewhat of a spook
# Other APIs do this however, and it saves code. As such, do it.
our %API = map {
    $_ => {
        needs_role       => "CalendarContact",
        needs_feature    => { match => 'all', features => [qw(caldavcarddav)] },
        worker_node_type => 'Mail',
    };
} qw{add_delegate update_delegate remove_delegate list_delegates list_users};

sub _boilerplate {
    my ( $args,      $result )    = @_;
    my ( $delegator, $delegatee ) = $args->get_length_required(qw{delegator delegatee});
    die "Delegator cannot be the same as delegatee" if $delegator eq $delegatee;
    my ($readonly) = $args->get('readonly');

    my %arg_hash = (
        'delegator' => $delegator,
        'delegatee' => $delegatee,
        'readonly'  => $readonly,
    );

    return ( \%arg_hash, $result );
}

sub _manage {
    my $action = shift;
    my ( $args, $result ) = _boilerplate(@_);
    my $res = Cpanel::AdminBin::Call::call( 'Cpanel', 'ccs', 'MANAGE_DELEGATIONS', $args->{'delegator'}, $args->{'delegatee'}, $args->{'readonly'}, $action );
    return 1;
}

sub add_delegate {
    return _manage( 'INSERT', @_ );
}

sub update_delegate {
    return _manage( 'UPDATE', @_ );
}

sub remove_delegate {
    return _manage( 'DELETE', @_ );
}

sub list_delegates {
    my ( $args, $result ) = @_;

    my $res = Cpanel::AdminBin::Call::call( 'Cpanel', 'ccs', 'GET_DELEGATIONS' );
    if ($res) {
        $result->data($res);
        return 1;
    }
    return 0;
}

sub list_users {
    my ( $args, $result ) = @_;

    my $res = Cpanel::AdminBin::Call::call( 'Cpanel', 'ccs', 'GET_CCS_USERS' );
    if ($res) {
        $result->data($res);
        return 1;
    }
    return 0;
}

1;
