import {
  buildSearchUrl,
  type SearchParams,
} from "@/lib/mail-search/search-params"

export type MailSearchRouter = {
  push: (url: string, options?: { scroll?: boolean }) => void
}

export type QuickSearchChipState = {
  chipAttachment?: boolean
  chipLast7Days?: boolean
  chipFromMe?: boolean
  fromEmail?: string
}

/** Build params from bar/overlay quick search + filter chips. */
export function buildQuickSearchParams(
  query: string,
  chips: QuickSearchChipState = {}
): Partial<SearchParams> {
  const q = query.trim()
  if (!q && !chips.chipAttachment && !chips.chipLast7Days && !chips.chipFromMe) {
    return {}
  }
  const params: Partial<SearchParams> = { q }
  if (chips.chipAttachment) params.has = ["attachment"]
  if (chips.chipLast7Days) params.within = "1w"
  if (chips.chipFromMe && chips.fromEmail) params.from = chips.fromEmail
  return params
}

/** Navigate to `/mail/search` with encoded query params. */
export function submitMailSearch(
  router: MailSearchRouter,
  params: Partial<SearchParams>,
  options?: { scroll?: boolean; onAfter?: () => void }
): void {
  router.push(buildSearchUrl(params), { scroll: options?.scroll ?? false })
  options?.onAfter?.()
}
