import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { ComplianceService } from './compliance.service';

@Injectable()
export class DeletionSchedulerService {
  private readonly logger = new Logger(DeletionSchedulerService.name);

  constructor(private readonly complianceService: ComplianceService) {}

  /**
   * Run daily at 2 AM to process account deletions that have passed the grace period
   */
  @Cron(CronExpression.EVERY_DAY_AT_2AM)
  async processPendingDeletions() {
    this.logger.log('Starting scheduled account deletion job...');

    try {
      const deletionRequests =
        await this.complianceService.getDeletionRequestsReadyForProcessing();

      this.logger.log(
        `Found ${deletionRequests.length} accounts ready for deletion`,
      );

      for (const request of deletionRequests) {
        try {
          this.logger.log(
            `Processing deletion for user ${request.userId} (request ID: ${request.id})`,
          );

          await this.complianceService.permanentlyDeleteAccount(request.userId);

          this.logger.log(
            `Successfully deleted account for user ${request.userId}`,
          );
        } catch (error) {
          this.logger.error(
            `Failed to delete account for user ${request.userId}: ${error.message}`,
            error.stack,
          );
        }
      }

      this.logger.log('Scheduled account deletion job completed');
    } catch (error) {
      this.logger.error(
        `Error running scheduled account deletion job: ${error.message}`,
        error.stack,
      );
    }
  }
}
