import { apiRequest } from '../lib/api'
import { getActiveBusinessId } from '../lib/businessContext'
import type {
  CategoryTechnicalForm,
  TechnicalFormFieldDraft,
  TechnicalFormField,
} from '../types/technicalForm'

function businessPath(categoryId: string) {
  const businessId = getActiveBusinessId()
  if (!businessId) {
    throw new Error('No active business selected. Please sign in again.')
  }
  return `/businesses/${businessId}/categories/${categoryId}/technical-form`
}

export function mapApiFieldToDraft(field: TechnicalFormField): TechnicalFormFieldDraft {
  return {
    id: field.id,
    label: field.label,
    type: field.type,
    isRequired: field.isRequired,
    options: field.options.map((option) => option.label),
  }
}

export function mapDraftToPayload(fields: TechnicalFormFieldDraft[]) {
  return {
    fields: fields.map((field) => ({
      label: field.label.trim(),
      type: field.type,
      isRequired: field.isRequired,
      ...(field.type === 'select' || field.type === 'multi_select'
        ? { options: field.options.map((option) => option.trim()).filter(Boolean) }
        : {}),
    })),
  }
}

export async function getCategoryTechnicalForm(categoryId: string, signal?: AbortSignal) {
  const data = await apiRequest<{ form: CategoryTechnicalForm | null }>(
    businessPath(categoryId),
    { auth: true, signal },
  )
  return data.form
}

export async function saveCategoryTechnicalForm(
  categoryId: string,
  fields: TechnicalFormFieldDraft[],
) {
  const data = await apiRequest<{ form: CategoryTechnicalForm | null }>(
    businessPath(categoryId),
    {
      method: 'PUT',
      auth: true,
      body: mapDraftToPayload(fields),
    },
  )
  return data.form
}

export async function suggestCategoryTechnicalFormByAi(
  categoryId: string,
  hint?: string,
) {
  const data = await apiRequest<{
    message: string
    fields: {
      label: string
      type: TechnicalFormFieldDraft['type']
      isRequired: boolean
      options?: string[]
    }[]
  }>(`${businessPath(categoryId)}/ai-suggest`, {
    method: 'POST',
    auth: true,
    body: hint ? { hint } : {},
  })

  return data.fields
}
