import { InternalServerErrorException } from '@nestjs/common';
import { QueryHandler, type IQueryHandler } from '@nestjs/cqrs';
import { DomainException, ForbiddenException, NotFoundException, LoggerService, PrismaService } from '@modules/shared';
import { GetSavedSearchQuery } from './get-saved-search.query';

export interface SavedSearchDetail {
  id: string;
  name: string;
  filters: unknown;
  alertEnabled: boolean;
  lastAlertAt: Date | null;
  createdAt: Date;
}

@QueryHandler(GetSavedSearchQuery)
export class GetSavedSearchHandler implements IQueryHandler<GetSavedSearchQuery> {
  constructor(
    private readonly prisma: PrismaService,
    private readonly logger: LoggerService,
  ) {}

  async execute(query: GetSavedSearchQuery): Promise<SavedSearchDetail> {
    try {
      const savedSearch = await this.prisma.savedSearch.findUnique({
        where: { id: query.id },
      });

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

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

      return {
        id: savedSearch.id,
        name: savedSearch.name,
        filters: savedSearch.filters,
        alertEnabled: savedSearch.alertEnabled,
        lastAlertAt: savedSearch.lastAlertAt,
        createdAt: savedSearch.createdAt,
      };
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to get saved search: ${error instanceof Error ? error.message : error}`,
        error instanceof Error ? error.stack : undefined,
        this.constructor.name,
      );
      throw new InternalServerErrorException('Không thể lấy thông tin tìm kiếm đã lưu');
    }
  }
}
