import { apiRequest } from '../lib/api'
import { getActiveBusinessId } from '../lib/businessContext'
import type {
  ContactSubmission,
  ContactSubmissionsListResponse,
} from '../types/contactSubmission'

export interface ListContactSubmissionsParams {
  page?: number
  pageSize?: number
  q?: string
}

function basePath() {
  const businessId = getActiveBusinessId()
  if (!businessId) {
    throw new Error('No active business selected. Please sign in again.')
  }
  return `/businesses/${businessId}/contact-submissions`
}

export async function listContactSubmissions(
  params: ListContactSubmissionsParams,
  signal?: AbortSignal,
) {
  const q = new URLSearchParams()
  if (params.page !== undefined) q.set('page', String(params.page))
  if (params.pageSize !== undefined) q.set('pageSize', String(params.pageSize))
  if (params.q) q.set('q', params.q)

  const query = q.toString()
  const path = `${basePath()}${query ? `?${query}` : ''}`

  return apiRequest<ContactSubmissionsListResponse>(path, { auth: true, signal })
}

export async function getContactSubmission(submissionId: string, signal?: AbortSignal) {
  return apiRequest<{ submission: ContactSubmission }>(`${basePath()}/${submissionId}`, {
    auth: true,
    signal,
  })
}
