import { InternalServerErrorException } from '@nestjs/common';
import { CommandHandler, type ICommandHandler } from '@nestjs/cqrs';
import { LoggerService, PrismaService, DomainException, NotFoundException, ValidationException } from '@modules/shared';
import { CancelUserDeletionCommand } from './cancel-user-deletion.command';

@CommandHandler(CancelUserDeletionCommand)
export class CancelUserDeletionHandler implements ICommandHandler<CancelUserDeletionCommand> {
  constructor(
    private readonly prisma: PrismaService,
    private readonly logger: LoggerService,
  ) {}

  async execute(command: CancelUserDeletionCommand): Promise<{ message: string }> {
    try {
      const user = await this.prisma.user.findUnique({ where: { id: command.userId } });
      if (!user) throw new NotFoundException('User', command.userId);
      if (user.deletedAt) throw new ValidationException('Tài khoản đã bị xóa vĩnh viễn');
      if (!user.deletionScheduledAt) throw new ValidationException('Không có yêu cầu xóa nào đang chờ');

      await this.prisma.user.update({
        where: { id: command.userId },
        data: { deletionScheduledAt: null, isActive: true },
      });

      this.logger.log(`User ${command.userId} deletion cancelled`, 'CancelUserDeletionHandler');
      return { message: 'Đã hủy yêu cầu xóa tài khoản' };
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to cancel user deletion: ${error instanceof Error ? error.message : error}`,
        error instanceof Error ? error.stack : undefined,
        this.constructor.name,
      );
      throw new InternalServerErrorException('Không thể hủy yêu cầu xóa tài khoản');
    }
  }
}
