import type { MessageSearchFilter } from "@/lib/api/types"
import type { SearchParams } from "@/lib/mail-search/search-params"

const WITHIN_MS: Record<string, number> = {
  "1d": 86_400_000,
  "3d": 3 * 86_400_000,
  "1w": 7 * 86_400_000,
  "2w": 14 * 86_400_000,
  "1m": 30 * 86_400_000,
  "2m": 60 * 86_400_000,
  "6m": 180 * 86_400_000,
  "1y": 365 * 86_400_000,
}

function withinToDateFromISO(within: string): string | undefined {
  const ms = WITHIN_MS[within]
  if (!ms) return undefined
  return new Date(Date.now() - ms).toISOString()
}

function parseDateParamToISO(value: string): string | undefined {
  const trimmed = value.trim()
  if (!trimmed) return undefined
  const parsed = new Date(trimmed)
  if (Number.isNaN(parsed.getTime())) return undefined
  return parsed.toISOString()
}

/** Text shown in the search bar from URL params. */
export function searchParamsToDisplayQuery(params: SearchParams | null): string {
  if (!params) return ""
  return params.q || params.hasWords || ""
}

/** Map URL search params to the backend `/mail/search` filter. */
export function searchParamsToMessageSearchFilter(
  params: SearchParams,
  accountId?: string
): MessageSearchFilter {
  const dateFrom =
    parseDateParamToISO(params.after) ??
    (params.within ? withinToDateFromISO(params.within) : undefined)

  return {
    q: params.q || params.hasWords || undefined,
    from: params.from || undefined,
    label:
      params.in !== "all" && params.in !== "all-spam" ? params.in : undefined,
    account_id: accountId,
    date_from: dateFrom,
    date_to: parseDateParamToISO(params.before),
    has_attachment: params.has.includes("attachment") ? true : undefined,
  }
}

export function isMessageSearchFilterActive(
  filter: MessageSearchFilter | null | undefined
): boolean {
  if (!filter) return false
  return !!(
    filter.q ||
    filter.from ||
    filter.label ||
    filter.date_from ||
    filter.date_to ||
    filter.has_attachment !== undefined
  )
}
