/**
 * GraphQL Subscription implementations
 * These are the actual subscription resolvers that publish events
 */

import { PubSub } from 'graphql-subscriptions'
import { Context } from '../types/context'

// Create a simple in-memory PubSub instance
// In production, use Redis or another pub/sub system
export const pubsub = new PubSub()

// Event channels
export const EVENTS = {
  RESOURCE_CREATED: 'RESOURCE_CREATED',
  RESOURCE_UPDATED: 'RESOURCE_UPDATED',
  RESOURCE_DELETED: 'RESOURCE_DELETED',
} as const

// Helper functions to publish events
export function publishResourceCreated(resource: any) {
  pubsub.publish(EVENTS.RESOURCE_CREATED, {
    resourceCreated: resource,
  })
}

export function publishResourceUpdated(resourceId: string, resource: any) {
  pubsub.publish(EVENTS.RESOURCE_UPDATED, {
    resourceUpdated: resource,
  })
}

export function publishResourceDeleted(resourceId: string) {
  pubsub.publish(EVENTS.RESOURCE_DELETED, {
    resourceDeleted: resourceId,
  })
}

// Subscription resolvers
export const subscriptionResolvers = {
  Subscription: {
    resourceCreated: {
      subscribe: () => pubsub.asyncIterator([EVENTS.RESOURCE_CREATED]),
    },
    resourceUpdated: {
      subscribe: (_: unknown, args: { id: string }) => {
        return pubsub.asyncIterator([EVENTS.RESOURCE_UPDATED])
      },
      resolve: (payload: any) => {
        // Filter by id if provided
        return payload.resourceUpdated
      },
    },
    resourceDeleted: {
      subscribe: (_: unknown, args: { id: string }) => {
        return pubsub.asyncIterator([EVENTS.RESOURCE_DELETED])
      },
      resolve: (payload: any) => {
        return payload.resourceDeleted
      },
    },
  },
}

