package Whostmgr::CometBackup::Hooks::AccountsRemove;

#                                      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 Whostmgr::CometBackup::DeletedUsers ();
use Whostmgr::CometBackup::Logger       ();

my $logger;

sub _get_logger {
    return $logger //= Whostmgr::CometBackup::Logger->new( log_level => $ENV{DEBUG} ? 'debug' : 'info' );
}

=encoding utf-8

=head1 NAME

Whostmgr::CometBackup::Hooks::AccountsRemove - Track deleted users for Comet backup retention

=head1 DESCRIPTION

This module provides hooks into the account removal process to track deleted cPanel
users in the Comet backup system. It uses both pre and post hooks:

=over 4

=item * B<pre-hook>: Records a placeholder deleted-user entry BEFORE the account is
removed so retention tracking already reflects the pending deletion.

=item * B<post-hook>: Confirms the deletion and updates the last_seen_deleted_ts
timestamp after the account has been removed from cPanel.

=back

=head1 SYNOPSIS

This module is registered as a hook with the cPanel hook system. It does not need
to be called directly.

    # Hook registration (done by plugin installation):
    /usr/local/cpanel/bin/manage_hooks add module Whostmgr::CometBackup::Hooks::AccountsRemove

=head1 STATIC METHODS

=head2 describe()

Returns an array reference of hook descriptors that define when and how
this module's hooks should be executed by the cPanel hook system.

=cut

sub describe {
    return [
        {
            'category' => 'Whostmgr',
            'event'    => 'Accounts::Remove',
            'stage'    => 'pre',
            'hook'     => 'Whostmgr::CometBackup::Hooks::AccountsRemove::pre_remove',
            'exectype' => 'module',
        },
        {
            'category' => 'Whostmgr',
            'event'    => 'Accounts::Remove',
            'stage'    => 'post',
            'hook'     => 'Whostmgr::CometBackup::Hooks::AccountsRemove::post_remove',
            'exectype' => 'module',
        },
    ];
}

=head2 pre_remove($context, $data)

Hook handler called before a cPanel account is removed. Captures the user's Comet
profile while they still exist in the Comet system, so we can retrieve their
backup snapshots, device IDs, and vault information later.

=over 4

=item B<Parameters:>

=over 4

=item * C<$context> - Hashref. Hook context information.

=item * C<$data> - Hashref. Account removal data including:
  - user: The username of the account being deleted
  - domain: The primary domain of the account

=back

=item B<Returns:>

Boolean value (1) indicating hook completed successfully.

=item B<Side Effects:>

Pre-creates a deleted_users record with Comet profile data before user deletion.
If the record already exists, updates it with the current Comet profile.

=back

=cut

sub pre_remove {
    my ( $context, $data ) = @_;

    my $logger   = _get_logger();
    my $username = $data->{user};

    unless ($username) {
        $logger->warn("Account removal pre-hook called without username");
        return 1;
    }

    $logger->debug("Recording deleted-user metadata before account removal: $username");

    eval {
        my $deleted_users = Whostmgr::CometBackup::DeletedUsers->new();

        # Pre-record the user so we preserve deletion timing even if later steps fail
        $deleted_users->record_deleted_user(
            system_user           => $username,
            estimated_usage_bytes => undef,       # Will be updated in post_remove if needed
        );

        $logger->debug("Successfully recorded deleted-user metadata for $username before deletion");
    };

    if ($@) {
        $logger->error("Failed to record deleted-user metadata for $username before deletion: $@");

        # Don't fail the account removal if this fails
    }

    return 1;
}

=head2 post_remove($context, $data)

Hook handler called after a cPanel account is removed. Updates the deletion
timestamp in the deleted_users database for backup retention tracking.

=over 4

=item B<Parameters:>

=over 4

=item * C<$context> - Hashref. Hook context information.

=item * C<$data> - Hashref. Account removal data including:
  - user: The username of the deleted account
  - uid: The UID of the deleted user
  - homedir: The home directory path
  - skipacctbak: Whether account backup was skipped

=back

=item B<Returns:>

Boolean value (1) indicating hook completed successfully.

=item B<Side Effects:>

Records the deleted user in the Comet deleted_users database.

=back

=cut

sub post_remove {
    my ( $context, $data ) = @_;

    my $logger   = _get_logger();
    my $username = $data->{user};

    unless ($username) {
        $logger->warn("Account removal post-hook called without username");
        return 1;
    }

    $logger->debug("Confirming deleted user record for Comet backup retention: $username");

    eval {
        my $deleted_users = Whostmgr::CometBackup::DeletedUsers->new();

        # Update last_seen_deleted_ts to confirm the deletion actually happened
        $deleted_users->record_deleted_user(
            system_user           => $username,
            estimated_usage_bytes => undef,       # Could add disk usage calculation here
        );

        $logger->debug("Successfully confirmed deleted user $username in Comet Backup database");
    };

    if ($@) {
        $logger->error("Failed to confirm deleted user $username in Comet Backup database: $@");

        # Don't fail the account removal if this fails
    }

    return 1;
}

=head1 DEPENDENCIES

=over 4

=item * Whostmgr::CometBackup::DeletedUsers - Database tracking for deleted users

=item * Whostmgr::CometBackup::Logger - Logging functionality

=back

=head1 LOGGING

The module logs:

=over 4

=item * User deletion events

=item * Database recording success/failure

=item * Any errors encountered during processing

=back

=head1 SEE ALSO

=over 4

=item * L<Whostmgr::CometBackup::DeletedUsers> - Deleted users database management

=item * L<Cpanel::Hooks> - cPanel hook system documentation

=back

=head1 AUTHOR

WebPros International, LLC

=head1 COPYRIGHT

Copyright 2025 WebPros International, LLC. All rights reserved.

=cut

1;
