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

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

export interface ProductTechnicalInfoResponse {
  form: CategoryTechnicalForm | null
  values: ProductTechnicalValue[]
  message?: string
}

export function valuesToFormState(
  form: CategoryTechnicalForm | null,
  values: ProductTechnicalValue[],
): ProductTechnicalFormValues {
  const state: ProductTechnicalFormValues = {}

  if (form) {
    for (const field of form.fields) {
      state[field.key] = field.type === 'multi_select' ? [] : ''
    }
  }

  for (const item of values) {
    if (item.value === null || item.value === undefined) continue
    state[item.fieldKey] = item.value
  }

  return state
}

export function formStateToPayload(values: ProductTechnicalFormValues) {
  return {
    values: Object.entries(values)
      .filter(([, value]) => {
        if (Array.isArray(value)) return value.length > 0
        return value !== ''
      })
      .map(([fieldKey, value]) => ({ fieldKey, value })),
  }
}

export async function getProductTechnicalInfo(productId: string, signal?: AbortSignal) {
  return apiRequest<ProductTechnicalInfoResponse>(businessPath(productId), {
    auth: true,
    signal,
  })
}

export async function saveProductTechnicalInfo(
  productId: string,
  values: ProductTechnicalFormValues,
) {
  return apiRequest<ProductTechnicalInfoResponse>(businessPath(productId), {
    method: 'PUT',
    auth: true,
    body: formStateToPayload(values),
  })
}
