import { serialize } from 'object-to-formdata'
import { httpClient } from '@/widgets/messages/services/HttpClient'
import { FoundMessage, Message } from '@/widgets/messages/types/Message'
import {
  CreateMessageDto,
  ReplyMessageDto,
  SearchMessagesDto,
  UpdateMessageDto,
} from '@/widgets/messages/dto/MessageDto'
import { MessageThread } from '@/widgets/messages/types/MessageThread'

class MessageHttpService {
  replyMessage(dto: ReplyMessageDto): Promise<MessageThread> {
    return httpClient
      .post<MessageThread>('message', this.serialize(dto))
      .then(response => response.data)
  }

  updateMessage(message: UpdateMessageDto): Promise<Message> {
    return httpClient
      .post<Message>(`message/${message.id}/update`, this.serialize(message))
      .then(response => response.data)
  }

  removeMessage(messageId: number): Promise<unknown> {
    return httpClient
      .post(`message/${messageId}/remove`)
      .then(response => response.data)
  }

  sendSmsMessage(dto: CreateMessageDto): Promise<Message> {
    return httpClient
      .post<Message>('message', dto)
      .then(response => response.data)
  }

  sendFeedbackMessage(dto: CreateMessageDto): Promise<Message> {
    return httpClient
      .post<Message>('message', this.serialize(dto))
      .then(response => response.data)
  }

  createThread(dto: CreateMessageDto): Promise<Message> {
    return httpClient
      .post<Message>('thread', this.serialize(dto))
      .then(response => response.data)
  }

  searchMessages(dto: SearchMessagesDto): Promise<FoundMessage[]> {
    return httpClient
      .post('/message/search', dto)
      .then(response => response.data)
  }

  private serialize(data: any) {
    return serialize(data, { indices: true, allowEmptyArrays: true })
  }
}

export default new MessageHttpService()
