import data from "@/data.json"
import { CardType } from "@/types/types"
import { NextRequest } from "next/server"

const cardData = data as CardType[]

export const dynamic = "force-dynamic" // defaults to auto
export async function GET(request: NextRequest) {
  // get search query from request
  const search = request.nextUrl.searchParams.get("search") || ""
  if (!search) {
    return Response.json([])
  }
  console.log(search)
  const cleanedSearch = search.replace(/[^a-zA-Z\s]/g, "").toLowerCase()
  const searchWords = cleanedSearch.split(/\s+/)
  const filteredData = cardData.filter((card) =>
    searchWords.some((word) =>
      card.caption
        ?.toLowerCase()
        .split(/[^a-z]/)
        .includes(word)
    )
  )

  return Response.json(filteredData)
}
