import apiClient from './client'
import type {
  SendJobListResponse,
  SendJobResponse,
  SendPecRequest,
} from '@/types/api.types'

export interface SendJobFilters {
  page?: number
  page_size?: number
  mailbox_id?: string
  status?: string
}

/** Payload esteso per l'invio multipart (include body_html) */
export interface SendPecMultipartRequest extends SendPecRequest {
  body_html?: string
}

export const sendApi = {
  /** Invio PEC semplice (JSON, senza allegati) – retrocompatibile */
  send: (data: SendPecRequest) =>
    apiClient.post<SendJobResponse>('/send', data).then((r) => r.data),

  /**
   * Invio PEC con allegati tramite multipart/form-data.
   *
   * Il campo `data` viene serializzato come JSON string;
   * i file vengono appesi come `attachments[]`.
   */
  sendMultipart: (data: SendPecMultipartRequest, files: File[] = []) => {
    const formData = new FormData()
    formData.append('data', JSON.stringify(data))
    files.forEach((file) => formData.append('attachments', file))
    return apiClient
      .post<SendJobResponse>('/send/multipart', formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
      })
      .then((r) => r.data)
  },

  listJobs: (filters: SendJobFilters = {}) =>
    apiClient.get<SendJobListResponse>('/send/jobs', { params: filters }).then((r) => r.data),

  getJob: (id: string) =>
    apiClient.get<SendJobResponse>(`/send/jobs/${id}`).then((r) => r.data),

  cancelJob: (id: string) => apiClient.delete(`/send/jobs/${id}`),
}
