import path from 'node:path'

export function slugify(input) {
  return String(input || '')
    .toLowerCase()
    .trim()
    .replace(/\s+/g, '-')
    .replace(/[^a-z0-9-а-яё]/gi, '')
}

export function safeExtFromFilename(filename) {
  const ext = path.extname(String(filename || '')).toLowerCase()
  const allowed = new Set(['.png', '.jpg', '.jpeg', '.webp'])
  return allowed.has(ext) ? ext : null
}

export function parseMaterialsInput(input) {
  if (Array.isArray(input)) {
    return input
      .map((x) => String(x || '').trim())
      .filter(Boolean)
      .slice(0, 30)
  }
  if (typeof input === 'string') {
    const s = input.trim()
    if (!s) return []
    return s
      .split(',')
      .map((x) => x.trim())
      .filter(Boolean)
      .slice(0, 30)
  }
  return []
}

export function materialsFromDb(materials) {
  if (Array.isArray(materials)) return materials
  try {
    const v = JSON.parse(String(materials || '[]'))
    return Array.isArray(v) ? v.map((x) => String(x || '').trim()).filter(Boolean) : []
  } catch {
    return []
  }
}

export function mapProductForApi(p, reviewsSummary = null) {
  const base = {
    ...p,
    materials: materialsFromDb(p.materials),
  }
  if (reviewsSummary && typeof reviewsSummary === 'object') {
    base.reviewsSummary = reviewsSummary
  }
  return base
}

