import { wrap } from "comlink"
import { LRUCache } from "lru-cache"
import type { OutputStyle } from "sass"
import type { Compiler } from "./compiler"

const worker = wrap<typeof Compiler>(
  new Worker(new URL("./compiler/compiler.js", import.meta.url).href, { type: "module" }),
)

const lru = new LRUCache<string, string>({ max: 450 })

export async function compileSASS(
  source: string,
  outputStyle: OutputStyle = "compressed",
  insertCache = true,
): Promise<string> {
  if (lru.has(source)) {
    return lru.get(source)!
  }

  try {
    const result = await worker.compileSASS(source, outputStyle)
    if (insertCache) {
      lru.set(source, result)
    }
    return result
  } catch (e) {
    if (process.env.NODE_ENV === "development") {
      console.error(e.message)
    }
    throw e
  }
}
