import type { WorkOrderRow } from '../../repositories/worker-platform/index.js'
import { safeParseJson } from '../admin/admin-query-utils.js'
import {
  refreshStoredFileUrl,
  refreshUploadedFileUrls,
} from '../file-storage/file-storage-service.js'
import {
  normalizeStringArray,
  normalizeSubmittedFields,
  normalizeUploadedFiles,
} from './worker-input-normalizers.js'

export function mapAcceptanceForResponse(value: unknown) {
  const acceptance = safeParseJson(value)
  const files = normalizeUploadedFiles(acceptance.files).map((file) =>
    refreshUploadedFileUrls(file),
  )
  const imageUrls = normalizeStringArray(acceptance.imageUrls).map((url) =>
    refreshStoredFileUrl(url),
  )
  return { ...acceptance, files, imageUrls }
}

export function resolveCollectSubmittedFieldValues(workOrder: WorkOrderRow) {
  const material = safeParseJson(workOrder.material_json)
  const collect =
    material.collect && typeof material.collect === 'object' && !Array.isArray(material.collect)
      ? safeParseJson(material.collect)
      : {}
  return normalizeSubmittedFields(collect.fields)
}
