import { parseAmount, parsePage } from "@/lib/utils";

export type SortKey = "featured" | "new" | "price-asc" | "price-desc" | "best-selling";

export const sortKeys: SortKey[] = ["featured", "new", "price-asc", "price-desc", "best-selling"];

export function parseSort(value: string | string[] | undefined): SortKey {
  const raw = Array.isArray(value) ? value[0] : value;
  return sortKeys.includes(raw as SortKey) ? (raw as SortKey) : "featured";
}

export function parseCatalogSearch(params: Record<string, string | string[] | undefined>) {
  const q = (Array.isArray(params.q) ? params.q[0] : params.q)?.trim().slice(0, 120) ?? "";
  const category = (Array.isArray(params.category) ? params.category[0] : params.category) ?? "";
  const min = parseAmount(params.min);
  const max = parseAmount(params.max);
  return {
    q,
    category,
    min: min !== undefined && max !== undefined && min > max ? max : min,
    max,
    inStock: params.inStock === "1",
    featured: params.featured === "1",
    sort: parseSort(params.sort),
    page: parsePage(params.page),
  };
}

export type CatalogSearch = ReturnType<typeof parseCatalogSearch>;
