import type { JsonObject } from '../../types/json.js'
import { normalizeStoredFileUrl } from '../file-storage/file-storage-service.js'
import { normalizeInteger } from './worker-normalizers.js'

export function normalizeSubmittedFields(value: unknown) {
  const source =
    value && typeof value === 'object' && !Array.isArray(value) ? (value as JsonObject) : {}
  return Object.fromEntries(
    Object.entries(source)
      .filter(([key]) => !['orderNo', 'platformOrderId', 'fields', 'material'].includes(key))
      .map(([key, currentValue]) => [key, String(currentValue || '').trim()]),
  )
}

export function normalizeStringArray(value: unknown): string[] {
  if (!Array.isArray(value)) return []
  return value.map((item) => String(item || '').trim()).filter(Boolean)
}

/** 将查询参数中的状态过滤解析为去重后的状态数组。 */
export function normalizeStatuses(value: unknown): string[] {
  const rawList: unknown[] = Array.isArray(value)
    ? value
    : typeof value === 'string' && value.trim()
      ? value.split(',')
      : value === undefined || value === null
        ? []
        : [value]
  return [...new Set(rawList.map((item) => String(item || '').trim()).filter(Boolean))]
}

export function normalizeUploadedFiles(value: unknown) {
  if (!Array.isArray(value)) return []
  return value
    .map((item) => {
      const source =
        item && typeof item === 'object' && !Array.isArray(item) ? (item as JsonObject) : {}
      const objectKey = String(source.objectKey || source.object_key || '').trim()
      const url = String(source.url || '').trim()
      if (!objectKey && !url) return null
      return {
        objectKey,
        url: normalizeStoredFileUrl(url, objectKey),
        thumbnailUrl: normalizeStoredFileUrl(
          source.thumbnailUrl || source.thumbnail_url || url,
          objectKey,
        ),
        mediumUrl: normalizeStoredFileUrl(source.mediumUrl || source.medium_url || url, objectKey),
        filename: String(source.filename || '').trim(),
        contentType: String(source.contentType || source.content_type || '').trim(),
        size: normalizeInteger(source.size, 0),
      }
    })
    .filter(
      (
        item,
      ): item is {
        objectKey: string
        url: string
        thumbnailUrl: string
        mediumUrl: string
        filename: string
        contentType: string
        size: number
      } => Boolean(item),
    )
}
