import axios from 'axios'
import { NotificationEvent } from '../types/NotificationEvent'

interface GetNotificationPayload {
  count?: number
  type?: string
  excludedTypes?: string[]
  projectId?: string
}

class NotificationService {
  backendHost!: string
  projectId!: string

  init(config: { backendHost: string; projectId: string }) {
    this.projectId = config.projectId
    this.backendHost =
      config.backendHost[config.backendHost.length - 1] === '/'
        ? config.backendHost.slice(0, -1)
        : config.backendHost
  }

  getNotifications(
    payload?: GetNotificationPayload
  ): Promise<{ notifications: NotificationEvent[]; count: number }> {
    const params: GetNotificationPayload = {
      count: payload?.count,
      projectId: this.projectId,
    }

    if (payload?.type) {
      params.type = payload?.type
    } else {
      params.excludedTypes = payload?.excludedTypes
    }

    return axios
      .get(`${this.backendHost}/notifications`, {
        params,
      })
      .then(response => response.data)
  }

  loadTypes() {
    return axios
      .get(`${this.backendHost}/types`, {
        params: { projectId: this.projectId },
      })
      .then(response => response.data.types)
  }

  closeNotification(notificationId: number) {
    return axios.post(
      `${this.backendHost}/notifications/close/${notificationId}`
    )
  }

  closeAllNotifications() {
    return axios.post(`${this.backendHost}/notifications/close`, {
      projectId: this.projectId,
    })
  }
}

export default new NotificationService()
