import apiClient from './client'

export interface PecContactResponse {
  id: string
  tenant_id: string
  email: string
  name: string | null
  organization: string | null
  notes: string | null
  is_favorite: boolean
  auto_saved: boolean
  created_by: string | null
  created_at: string
  updated_at: string
}

export interface PecContactCreate {
  email: string
  name?: string | null
  organization?: string | null
  notes?: string | null
  is_favorite?: boolean
}

export interface PecContactUpdate {
  name?: string | null
  organization?: string | null
  notes?: string | null
  is_favorite?: boolean
}

export interface ContactImportResult {
  created: number
  updated: number
  skipped: number
  errors: string[]
}

export const contactsApi = {
  list: (params?: { q?: string; page?: number; page_size?: number }) =>
    apiClient.get<{ items: PecContactResponse[]; total: number }>('/contacts', { params }).then((r) => r.data),

  autocomplete: (q: string) =>
    apiClient.get<PecContactResponse[]>('/contacts/autocomplete', { params: { q } }).then((r) => r.data),

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

  create: (data: PecContactCreate) =>
    apiClient.post<PecContactResponse>('/contacts', data).then((r) => r.data),

  update: (id: string, data: PecContactUpdate) =>
    apiClient.put<PecContactResponse>(`/contacts/${id}`, data).then((r) => r.data),

  delete: (id: string) =>
    apiClient.delete(`/contacts/${id}`).then((r) => r.data),

  importCsv: (file: File) => {
    const formData = new FormData()
    formData.append('file', file)
    return apiClient.post<ContactImportResult>('/contacts/import', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    }).then((r) => r.data)
  },
}
