import { InternalServerErrorException } from '@nestjs/common';
import { CommandHandler, type ICommandHandler } from '@nestjs/cqrs';
import { DomainException, ForbiddenException, NotFoundException, PrismaService, LoggerService } from '@modules/shared';
import { DeleteSavedSearchCommand } from './delete-saved-search.command';

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

  async execute(command: DeleteSavedSearchCommand): Promise<{ deleted: boolean }> {
    try {
      const savedSearch = await this.prisma.savedSearch.findUnique({
        where: { id: command.id },
      });

      if (!savedSearch) {
        throw new NotFoundException('SavedSearch', command.id);
      }

      if (savedSearch.userId !== command.userId) {
        throw new ForbiddenException('Bạn không có quyền xóa tìm kiếm này');
      }

      await this.prisma.savedSearch.delete({ where: { id: command.id } });

      this.logger.log(`Saved search deleted: id=${command.id}, user=${command.userId}`, 'DeleteSavedSearchHandler');

      return { deleted: true };
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to delete saved search: ${error instanceof Error ? error.message : error}`,
        error instanceof Error ? error.stack : undefined,
        this.constructor.name,
      );
      throw new InternalServerErrorException('Không thể xóa tìm kiếm đã lưu');
    }
  }
}
