import { apiClient } from './client'
import type {
  PSAResource,
  PSATicketCreated,
  PSATicketStatusUpdate,
  TicketCreationPayload,
  AiParseResponse,
  TicketListResponse,
  PSAPriority,
} from '@/types/tickets'

export const ticketsApi = {
  listResources: (ticketId: number): Promise<PSAResource[]> =>
    apiClient.get<PSAResource[]>(`/integrations/psa/tickets/${ticketId}/resources`).then(r => r.data),

  addResource: (ticketId: number, memberId: number): Promise<PSAResource> =>
    apiClient.post<PSAResource>(`/integrations/psa/tickets/${ticketId}/resources?member_id=${memberId}`).then(r => r.data),

  removeResource: (ticketId: number, memberId: number): Promise<void> =>
    apiClient.delete(`/integrations/psa/tickets/${ticketId}/resources/${memberId}`).then(() => undefined),

  updateStatus: (ticketId: number, statusId: number): Promise<PSATicketStatusUpdate> =>
    apiClient.patch<PSATicketStatusUpdate>(`/integrations/psa/tickets/${ticketId}/status?status_id=${statusId}`).then(r => r.data),

  createTicket: (payload: TicketCreationPayload): Promise<PSATicketCreated> =>
    apiClient.post<PSATicketCreated>('/integrations/psa/tickets', payload).then(r => r.data),

  aiParse: (prompt: string): Promise<AiParseResponse> =>
    apiClient.post<AiParseResponse>('/integrations/psa/tickets/ai-parse', { prompt }).then(r => r.data),

  listPriorities: (): Promise<PSAPriority[]> =>
    apiClient.get<PSAPriority[]>('/integrations/psa/priorities').then(r => r.data),

  searchTickets: (params: {
    query?: string
    board_id?: number | null
    status_id?: number | null
    status_name?: string | null
    include_closed?: boolean
    assigned_to_me?: boolean
    unassigned?: boolean
    board_ids?: string
    priority?: string | null
    company_id?: number | null
    page?: number
    page_size?: number
  }): Promise<TicketListResponse> =>
    apiClient.get<TicketListResponse>('/integrations/psa/tickets/search', { params }).then(r => r.data),
}
