import { MessageThread } from '@/widgets/messages/types/MessageThread'
import { MessageFilterType } from '@/widgets/messages/types/CountingMessages'
import { httpClient } from '@/widgets/messages/services/HttpClient'
import { ThreadSubject } from '@/widgets/messages/types/ThreadSubject'

export type GetThreadsPayload = {
  ids?: number[]
  type?: MessageFilterType
  orderName?: string
}

export type ChangeThreadSubjectPayload = {
  threadId: number
  subjectId?: number
  orderName?: string
}

export type ChangeThreadOrderPayload = {
  threadId: number
  orderName: string
}

export type UpdateManagersInThread = {
  threadId: number
  managerUids: string[]
}

class ThreadService {
  getThreadById(threadId: number): Promise<MessageThread> {
    return httpClient.get(`/thread/${threadId}`).then(response => response.data)
  }

  getThreads(payload?: GetThreadsPayload): Promise<MessageThread[]> {
    return httpClient
      .post<MessageThread[]>('threads', payload, { withCredentials: true })
      .then(response => response.data)
  }

  getThreadSubjects(): Promise<ThreadSubject[]> {
    return httpClient
      .get<ThreadSubject[]>('subjects')
      .then(response => response.data)
  }

  addThreadToFavorite(threadId: number): Promise<MessageThread> {
    return httpClient
      .post<MessageThread>(`threads/${threadId}/add-to-favorite`)
      .then(response => response.data)
  }

  removeThreadFromFavorite(threadId: number): Promise<MessageThread> {
    return httpClient
      .post<MessageThread>(`threads/${threadId}/remove-from-favorite`)
      .then(response => response.data)
  }

  closeThread(threadId: number): Promise<MessageThread> {
    return httpClient
      .post<MessageThread>(`thread/${threadId}/close`)
      .then(response => response.data)
  }

  openThread(threadId: number): Promise<MessageThread> {
    return httpClient
      .post<MessageThread>(`thread/${threadId}/open`)
      .then(response => response.data)
  }

  changeThreadOrder(payload: ChangeThreadOrderPayload) {
    return httpClient
      .post<MessageThread>(`thread/${payload.threadId}/change-order`, {
        orderName: payload.orderName,
      })
      .then(response => response.data)
  }

  changeThreadSubject(
    payload: ChangeThreadSubjectPayload
  ): Promise<MessageThread> {
    return httpClient
      .post<MessageThread>(`thread/${payload.threadId}/change-subject`, {
        subjectId: payload.subjectId,
        orderName: payload.orderName,
      })
      .then(response => response.data)
  }

  updateManagersInThread(
    payload: UpdateManagersInThread
  ): Promise<MessageThread> {
    return httpClient
      .post<MessageThread>(
        `thread/${payload.threadId}/update-managers`,
        payload.managerUids
      )
      .then(response => response.data)
  }
}

export default new ThreadService()
