import { SubscriberArgs, SubscriberConfig } from '@medusajs/framework'
import { ContainerRegistrationKeys, Modules } from '@medusajs/framework/utils'

import { AlgoliaEvents, IntermediateEvents } from '../modules/algolia/types'
import sellerFulfillmentSet from '@mercurjs/core/links/fulfillment-set-seller-link'
import productSellerLink from '@mercurjs/core/links/product-seller-link'

export default async function fulfillmentSetChangedHandler({
  event,
  container
}: SubscriberArgs<{ id: string }>) {
  const fulfillment_set_id = event.data.id
  const query = container.resolve(ContainerRegistrationKeys.QUERY)
  const eventBus = container.resolve(Modules.EVENT_BUS)

  const {
    data: [seller]
  } = await query.graph({
    entity: sellerFulfillmentSet.entryPoint,
    fields: ['seller_id'],
    filters: {
      fulfillment_set_id
    },
    withDeleted: true
  })

  if (!seller) {
    return
  }

  const { data: products } = await query.graph({
    entity: productSellerLink.entryPoint,
    fields: ['product_id'],
    filters: {
      seller_id: seller.seller_id
    }
  })

  await eventBus.emit({
    name: AlgoliaEvents.PRODUCTS_CHANGED,
    data: { ids: products.map((p) => p.product_id) }
  })
}

export const config: SubscriberConfig = {
  event: IntermediateEvents.FULFILLMENT_SET_CHANGED,
  context: {
    subscriberId: 'fulfillment-set-changed-handler'
  }
}
