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

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

export interface SavedSearchListResult {
  data: SavedSearchItem[];
  total: number;
  page: number;
  limit: number;
}

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

  async execute(query: GetSavedSearchesQuery): Promise<SavedSearchListResult> {
    try {
      const skip = (query.page - 1) * query.limit;

      const [data, total] = await Promise.all([
        this.prisma.savedSearch.findMany({
          where: { userId: query.userId },
          orderBy: { createdAt: 'desc' },
          skip,
          take: query.limit,
        }),
        this.prisma.savedSearch.count({
          where: { userId: query.userId },
        }),
      ]);

      return {
        data: data.map((s) => ({
          id: s.id,
          name: s.name,
          filters: s.filters,
          alertEnabled: s.alertEnabled,
          lastAlertAt: s.lastAlertAt,
          createdAt: s.createdAt,
        })),
        total,
        page: query.page,
        limit: query.limit,
      };
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to get saved searches: ${error instanceof Error ? error.message : error}`,
        error instanceof Error ? error.stack : undefined,
        this.constructor.name,
      );
      throw new InternalServerErrorException('Không thể lấy danh sách tìm kiếm đã lưu');
    }
  }
}
