import { resolve } from 'node:path'
import type { Nuxt } from '@nuxt/schema'

type ModuleMeta = { name: string }
type NuxtModuleWithMeta = ((options: unknown, nuxt: Nuxt) => void) & { meta?: ModuleMeta }

const fixTailwindPostcss: NuxtModuleWithMeta = (_options, nuxt) => {
  nuxt.hook('modules:done', () => {
    const legacyBuildPostcss = (nuxt.options.build as unknown as { postcss?: unknown } | undefined)?.postcss
    const postcssOptions =
      nuxt.options.postcss ||
      (legacyBuildPostcss as { postcssOptions?: unknown } | undefined)?.postcssOptions ||
      legacyBuildPostcss

    if (!postcssOptions) return

    const plugins = ((postcssOptions as { plugins?: Record<string, unknown> }).plugins ||= {})
    plugins.tailwindcss = {
      config: resolve(nuxt.options.rootDir, 'tailwind.config.cjs')
    }
  })
}

fixTailwindPostcss.meta = { name: 'fix-tailwind-postcss' }

export default fixTailwindPostcss
