import apiClient from './client'
import type {
  AttachmentResponse,
  MessageListResponse,
  MessageResponse,
} from '@/types/api.types'

export interface MessageFilters {
  page?: number
  page_size?: number
  mailbox_id?: string
  direction?: 'inbound' | 'outbound'
  state?: string
  is_read?: boolean
  is_starred?: boolean
  is_archived?: boolean
  search?: string
}

export const messagesApi = {
  list: (filters: MessageFilters = {}) =>
    apiClient
      .get<MessageListResponse>('/messages', { params: filters })
      .then((r) => r.data),

  get: (id: string) =>
    apiClient.get<MessageResponse>(`/messages/${id}`).then((r) => r.data),

  markRead: (id: string) =>
    apiClient.patch<MessageResponse>(`/messages/${id}`, { is_read: true }).then((r) => r.data),

  markUnread: (id: string) =>
    apiClient.patch<MessageResponse>(`/messages/${id}`, { is_read: false }).then((r) => r.data),

  toggleStar: (id: string, starred: boolean) =>
    apiClient
      .patch<MessageResponse>(`/messages/${id}`, { is_starred: starred })
      .then((r) => r.data),

  archive: (id: string) =>
    apiClient
      .patch<MessageResponse>(`/messages/${id}`, { is_archived: true })
      .then((r) => r.data),

  getAttachments: (id: string) =>
    apiClient.get<AttachmentResponse[]>(`/messages/${id}/attachments`).then((r) => r.data),

  getAttachmentUrl: (messageId: string, attachmentId: string) =>
    `/api/v1/messages/${messageId}/attachments/${attachmentId}/download`,

  getReceipts: (id: string) =>
    apiClient.get<MessageResponse[]>(`/messages/${id}/receipts`).then((r) => r.data),
}
