import { defineNuxtModule, createResolver, addPlugin, addImports, addTemplate } from '@nuxt/kit';

const module = defineNuxtModule({
  meta: {
    name: "dayjs",
    configKey: "dayjs",
    compatibility: {
      nuxt: "^3"
    }
  },
  // Default configuration options of the Nuxt module
  defaults: {
    locales: [],
    plugins: ["relativeTime", "utc"],
    defaultLocale: void 0,
    defaultTimezone: void 0
  },
  setup(options, nuxt) {
    const resolver = createResolver(import.meta.url);
    options.plugins = [...new Set(options.plugins)];
    if (options.defaultTimezone && !options.plugins.includes("timezone"))
      throw new Error("You must include the timezone plugin in order to set a default timezone");
    addPlugin(resolver.resolve("./runtime/plugin"));
    addImports({
      name: "useDayjs",
      as: "useDayjs",
      from: resolver.resolve("./runtime/composables/dayjs")
    });
    addTemplate({
      filename: "dayjs.imports.mjs",
      getContents: () => generateImports(options)
    });
    nuxt.hook("prepare:types", ({ references }) => {
      if (options.plugins) {
        const plugins = options.plugins.map((p) => ({ types: `dayjs/plugin/${p}` }));
        references.push(...plugins);
      }
    });
  }
});
const generateImports = ({ locales, plugins, defaultLocale, defaultTimezone, relativeTime }) => `
// Generated by dayjs-nuxt-module
import dayjs from 'dayjs'
${locales?.map((locale) => `import 'dayjs/locale/${locale}'`).join("\n")}
${plugins?.map((plugin) => `import ${plugin} from 'dayjs/plugin/${plugin}'`).join("\n")}
${relativeTime ? "import updateLocale from 'dayjs/plugin/updateLocale'" : ""}

${plugins?.map((plugin) => `dayjs.extend(${plugin})`).join("\n")}
${relativeTime ? "dayjs.extend(updateLocale)" : ""}
${locales?.map((locale) => `dayjs.locale('${locale}')`).join("\n")}
${defaultTimezone ? `dayjs.tz.setDefault('${defaultTimezone}')` : ""}

${relativeTime ? `
dayjs.updateLocale('${defaultLocale}', {
  relativeTime: {
    future: "${relativeTime.future}",
    past: "${relativeTime.past}",
    s: '${relativeTime.s}',
    m: "${relativeTime.m}",
    mm: "${relativeTime.mm}",
    h: "${relativeTime.h}",
    hh: "${relativeTime.hh}",
    d: "${relativeTime.d}",
    dd: "${relativeTime.dd}",
    M: "${relativeTime.M}",
    MM: "${relativeTime.MM}",
    y: "${relativeTime.y}",
    yy: "${relativeTime.yy}",
  }
})` : ""}

export default dayjs
`;

export { module as default };
