import { Inject, Injectable, Logger } from '@nestjs/common';
import { RevokeShareCommand } from './revoke-share.command';
import { BACKUP_SHARE_REPOSITORY } from '../../../domain';
import type { BackupShareRepository } from '../../../domain';
import { AuditLogRepository } from '../../../infrastructure/persistence/repositories/audit-log.repository';
import { ApplicationError } from '../../errors/application.error';

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

  constructor(
    @Inject(BACKUP_SHARE_REPOSITORY)
    private readonly repository: BackupShareRepository,
    private readonly auditLogRepository: AuditLogRepository,
  ) {}

  async execute(command: RevokeShareCommand): Promise<void> {
    this.logger.log(`Revoking backup share for user: ${command.userId}`);

    const userId = BigInt(command.userId);

    // Find share
    const share = await this.repository.findByUserIdAndPublicKey(
      userId,
      command.publicKey,
    );

    if (!share) {
      throw new ApplicationError(
        'Backup share not found',
        'SHARE_NOT_FOUND',
      );
    }

    // Revoke the share
    share.revoke(command.reason);

    // Save changes
    await this.repository.save(share);

    // Log audit
    await this.auditLogRepository.log({
      shareId: share.shareId!,
      userId,
      action: 'REVOKE',
      sourceService: command.sourceService,
      sourceIp: command.sourceIp,
      success: true,
    });

    this.logger.log(`Backup share revoked: shareId=${share.shareId}, reason=${command.reason}`);
  }
}
