import type { ListingCategoryId } from '@/data/listing-field-options'

/** Mapowanie ID kategorii OLX → nasze listing_categories.id */
const OLX_TO_CATEGORY: Record<number, ListingCategoryId> = {
  5016: 'sail',
  5011: 'power',
  5010: 'inflatable',
  5013: 'engine',
  5012: 'engine',
  5014: 'small',
  5015: 'small',
  5008: 'small',
  5009: 'accessories',
  5017: 'accessories',
  5018: 'berth',
  5019: 'accessories',
  5020: 'accessories',
}

export function mapOlxCategoryToListing(olxCategoryId: number | null | undefined): ListingCategoryId {
  if (olxCategoryId != null && OLX_TO_CATEGORY[olxCategoryId]) {
    return OLX_TO_CATEGORY[olxCategoryId]
  }
  return 'power'
}

/** OLX normalized_name → slug województwa (POLISH_VOIVODESHIPS). */
export function mapOlxRegionToSlug(normalizedName: string | null | undefined): string | null {
  if (!normalizedName?.trim()) return null
  const n = normalizedName.trim().toLowerCase()
  const map: Record<string, string> = {
    dolnoslaskie: 'dolnośląskie',
    'kujawsko-pomorskie': 'kujawsko-pomorskie',
    lubelskie: 'lubelskie',
    lubuskie: 'lubuskie',
    lodzkie: 'łódzkie',
    malopolskie: 'małopolskie',
    mazowieckie: 'mazowieckie',
    opolskie: 'opolskie',
    podkarpackie: 'podkarpackie',
    podlaskie: 'podlaskie',
    pomorskie: 'pomorskie',
    slaskie: 'śląskie',
    swietokrzyskie: 'świętokrzyskie',
    'warminsko-mazurskie': 'warmińsko-mazurskie',
    wielkopolskie: 'wielkopolskie',
    zachodniopomorskie: 'zachodniopomorskie',
  }
  return map[n] ?? null
}

/** Próba wyciągnięcia roku z tytułu/opisu. */
export function extractYearFromText(...parts: (string | null | undefined)[]): number | null {
  const text = parts.filter(Boolean).join(' ')
  const maxYear = new Date().getFullYear() + 1
  const yearsFrom = (value: string) =>
    (value.match(/\b(?:19\d{2}|20\d{2})\b/g) ?? [])
      .map((match) => Number.parseInt(match, 10))
      .filter((year) => year >= 1900 && year <= maxYear)

  const titleYears = yearsFrom(parts[0] ?? '')
  if (titleYears.length > 0) return titleYears[0]

  const explicit = text.match(/(?:rok(?:\s+(?:budowy|produkcji))?|rocznik)\D{0,16}(19\d{2}|20\d{2})/i)
  if (explicit) {
    const year = Number.parseInt(explicit[1], 10)
    if (year >= 1900 && year <= maxYear) return year
  }

  const years = yearsFrom(text)
  if (!years.length) return null
  // Najstarszy rok jest zwykle rokiem jednostki; późniejsze daty często opisują remont lub silnik.
  return Math.min(...years)
}

/** Proste czyszczenie HTML opisu OLX do tekstu. */
export function stripHtmlToText(html: string | null | undefined): string {
  if (!html?.trim()) return ''
  return html
    .replace(/<br\s*\/?>/gi, '\n')
    .replace(/<\/p>/gi, '\n')
    .replace(/<[^>]+>/g, '')
    .replace(/&nbsp;/g, ' ')
    .replace(/&amp;/g, '&')
    .replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>')
    .replace(/\n{3,}/g, '\n\n')
    .trim()
}
