import * as sdk from '@botpress/sdk'
import { BASE_EVENT_PAYLOAD } from 'definitions/events'
import * as filesReadonly from '../../files-readonly'
import { NotionClient } from '../../notion-api'
import * as bp from '.botpress'

const NOTIFICATION_PAYLOAD = BASE_EVENT_PAYLOAD.extend({
  type: sdk.z.literal('database.deleted'),
  entity: BASE_EVENT_PAYLOAD.shape.entity.extend({
    type: sdk.z.literal('database'),
  }),
})

export const isDatabaseDeletedEvent = (props: bp.HandlerProps): boolean =>
  Boolean(
    props.req.method.toUpperCase() === 'POST' &&
      props.req.body?.length &&
      NOTIFICATION_PAYLOAD.safeParse(JSON.parse(props.req.body)).success
  )

export const handleDatabaseDeletedEvent: bp.IntegrationProps['handler'] = async (props) => {
  const payload: sdk.z.infer<typeof NOTIFICATION_PAYLOAD> = JSON.parse(props.req.body!)

  const notionClient = await NotionClient.create(props)
  // Try to get as data source first (new API)
  const deletedDataSource = await notionClient.getDataSource({ dataSourceId: payload.entity.id })

  if (!deletedDataSource) {
    console.debug(`Notion data source ${payload.entity.id} not found. Ignoring database.deleted event.`)
    return
  }

  const dataSourceName = filesReadonly.getDataSourceTitle(deletedDataSource)
  const parentPath = await filesReadonly.retrieveParentPath(deletedDataSource.parent, notionClient)
  const absolutePath = `/${parentPath}/${dataSourceName}`

  await props.client.createEvent({
    type: 'folderDeletedRecursive',
    payload: {
      folder: {
        ...filesReadonly.mapDataSourceToFolder(deletedDataSource),
        absolutePath,
      },
    },
  })
}
