import { dirname } from "path"
import { promises as fs } from "fs"
import * as esbuild from "esbuild"

export const stringImport = (): esbuild.Plugin => ({
  name: "stringImport",
  setup(build) {
    build.onResolve({ filter: /\?string$/ }, async ({ path, importer }) => {
      const resolved = await build.resolve(path.replace(/\?string$/, ""), {
        kind: "import-statement",
        importer,
        resolveDir: dirname(importer),
      })

      return {
        namespace: stringImport.name,
        path: resolved.path,
      }
    })

    build.onLoad({ filter: /.*/, namespace: stringImport.name }, async ({ path }) => {
      let code = await fs.readFile(path, "utf-8")
      if (build.initialOptions.minify && path.endsWith(".css")) {
        ;({ code } = await esbuild.transform(code, { loader: "css", minify: true }))
      }
      return {
        contents: code,
        loader: "text",
      }
    })
  },
})
