import { Injectable } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import { ProductsService } from './products.service';
import { MediasService } from '../medias/medias.service';

@Injectable()
export class ProductsListener {
  constructor(
    private readonly service: ProductsService,
    private readonly mediaService: MediasService,
  ) {}

  @OnEvent('media.deleted')
  async handleMediaDeletedEvent(payload: {
    type: string;
    subdir: string;
    filename: string;
    filePath: string;
  }) {
    const id = this.mediaService.extractIdFromFilename(payload.filename);

    const product = await this.service.repo.findOne({ where: { id } });
    if (!product) return;

    // Loại bỏ ảnh trùng với filename
    product.images = product.images.filter(
      (image) => !image.includes(payload.filename),
    );

    await this.service.repo.update(product.id, product);
  }
}
