import { defineConfig } from '#q-app/wrappers'
import { fileURLToPath } from 'node:url';

import path from 'path'

// console.log(process.env)

export default defineConfig((ctx) => {
  return {
    // https://v2.quasar.dev/quasar-cli/supporting-ts

    // https://v2.quasar.dev/quasar-cli/prefetch-feature
    // preFetch: true,

    // app boot file (/src/boot)
    // --> boot files are part of "main.js"
    // https://v2.quasar.dev/quasar-cli/boot-files
    // boot: ['vue-i18n', 'vue-meta', 'axios', 'vee-validate', 'myconfig', 'local-storage', 'error-handler', 'globalroutines', 'vue-idb', 'dragula', 'guard'],
    boot: ['i18n', 'axios', 'pinia', 'vee-validate',
      'myconfig',
      'local-storage', 'error-handler', 'globalroutines',
      'calendar', 'social-sharing', 'timeago', 'guard'],

    // https://v2.quasar.dev/quasar-cli/quasar-conf-js#Property%3A-css
    css: [
      'app.scss',
      // '~quasar-ui-qcalendar/src/css/calendar-day.sass'
    ],

    // https://github.com/quasarframework/quasar/tree/dev/extras
    extras: [
      // 'ionicons-v4',
      // 'mdi-v5',
      // 'eva-icons',
      // 'themify',
      // 'line-awesome',
      'ionicons-v4',
      // 'mdi-v3',
      'fontawesome-v5',
      'roboto-font', // optional, you are not bound to it
      'material-icons', // optional, you are not bound to it
      'material-icons-outlined',
    ],

    // Full list of options: https://v2.quasar.dev/quasar-cli/quasar-conf-js#Property%3A-build

    build: {
      target: {
        browser: ['es2022', 'firefox115', 'chrome115', 'safari14'],
        node: 'node20'
      },
      sassVariables: 'src/css/variables.scss',
      // env: envparser(),
      // versionCode: package.version,
      vueRouterMode: 'history',
      analyze: false, // true
      transpile: true,
      transpileDependencies: [
        /quasar-ui-qcalendar[\\/]src/
      ],
      beforeDev(api) {
        // Se la variabile d'ambiente SKIP_TSC è impostata, disabilita il type checking
        if (process.env.SKIP_TSC === 'true') {
          console.log('⚠️ TypeScript type checking is disabled');

          // Disattiva TypeScript checking per Vite
          if (api && api.chainWebpack) {
            api.chainWebpack((chain) => {
              chain.plugin('fork-ts-checker').tap((args) => {
                args[0].typescript = false;
                return args;
              });
            });
          }
        }
      },
      // @quasar/app-vite v2.0.3+
      envFilter(originalEnv) {
        const newEnv = {}
        for (const key in originalEnv) {
          /* ...decide if it goes in or not... */
          if (true) {
            newEnv[key] = originalEnv[key]
          }
        }

        // remember to return your processed env
        return newEnv
      },

      typescript: {
        strict: false,
        vueShim: true,
        extendTsConfig(tsConfig) {
          // You can use this hook to extend tsConfig dynamically
          // For basic use cases, you can still update the usual tsconfig.json file to override some settings
        },

        /**
           * Folder where Quasar CLI should look for .env* files.
           * Can be an absolute path or a relative path to project root directory.
           *
           * @default project root directory
           */
        // envFolder?: string
        /**
         * Additional .env* files to be loaded.
         * Each entry can be an absolute path or a relative path to quasar.config > build > envFolder.
         *
         * @example ['.env.somefile', '../.env.someotherfile']
         */
        // envFiles?: string[];
      },

      extendViteConf(viteConf, { isServer, isClient }) {
        viteConf.resolve = {
          ...(viteConf.resolve || {}),
          alias: {
            ...viteConf.resolve.alias,
            '#q-app': path.resolve(__dirname, 'node_modules/quasar/app'), // Alias per #q-app
            'app': path.resolve(__dirname),
            'boot': path.resolve(__dirname, 'src/boot'),
            'src': path.resolve(__dirname, 'src'),
            'statics': path.resolve(__dirname, 'src/statics'),
            'components': path.resolve(__dirname, 'src/components'),
            'views': path.resolve(__dirname, 'src/views/index.ts'),
            'images': path.resolve(__dirname, 'src/assets/images'),
            'maps': path.resolve(__dirname, 'public/maps'),
            'classes': path.resolve(__dirname, 'src/classes/index.ts'),
            'fonts': path.resolve(__dirname, 'src/assets/fonts'),
            'utils': path.resolve(__dirname, 'src/utils/index.ts'),
            'css': path.resolve(__dirname, 'src/css/variables.scss'),
            'router': path.resolve(__dirname, 'src/router/index.ts'),
            'validators': path.resolve(__dirname, 'src/utils/validators.ts'),
            'methods': path.resolve(__dirname, 'src/utils/methods.ts'),
            'filters': path.resolve(__dirname, 'src/utils/filters.ts'),
            'api': path.resolve(__dirname, 'src/store/Api/index.ts'),
            'paths': path.resolve(__dirname, 'src/store/Api/ApiRoutes.ts'),
            'modules': path.resolve(__dirname, 'src/store/Modules/index.ts'),
            'model': path.resolve(__dirname, 'src/model/index.ts'),
            '@components': path.resolve(__dirname, 'src/components'),
            '@boot': path.resolve(__dirname, 'src/boot'),
            '@costanti': path.resolve(__dirname, 'src/store/Modules/costanti.ts'),
            '@views': path.resolve(__dirname, 'src/views/index.ts'),
            '@src': path.resolve(__dirname, 'src'),
            '@css': path.resolve(__dirname, 'src/public/css/variables.scss'),
            '@icons': path.resolve(__dirname, 'src/public/public/myicons'),
            '@images': path.resolve(__dirname, 'src/public/images/*'),
            '@maps': path.resolve(__dirname, 'src/public/maps/*'),
            '@classes': path.resolve(__dirname, 'src/classes/index.ts'),
            '@utils': path.resolve(__dirname, 'src/utils/index.ts'),
            '@router': path.resolve(__dirname, 'src/router/index.ts'),
            '@validators': path.resolve(__dirname, 'src/utils/validators.ts'),
            '@methods': path.resolve(__dirname, 'src/utils/methods.ts'),
            '@api': path.resolve(__dirname, 'src/store/Api/index.ts'),
            '@paths': path.resolve(__dirname, 'src/store/Api/ApiRoutes.ts'),
            '@storemod': path.resolve(__dirname, 'src/store/Modules'),
            '@store': path.resolve(__dirname, 'src/store'),
            '@tools': path.resolve(__dirname, 'src/store/Modules/tools.ts'),
            '@modules': path.resolve(__dirname, 'src/store/Modules/index.ts'),
            '@model': path.resolve(__dirname, 'src/model/index.ts'),
          },
        };
      },

      vitePlugins: [
        ['@intlify/unplugin-vue-i18n/vite', {
          // if you want to use Vue I18n Legacy API, you need to set `compositionOnly: false`
          // compositionOnly: false,

          // if you want to use named tokens in your Vue I18n messages, such as 'Hello {name}',
          // you need to set `runtimeOnly: false`
          // runtimeOnly: false,

          ssr: ctx.modeName === 'ssr',

          // you need to set i18n resource including paths !
          include: [fileURLToPath(new URL('./src/i18n', import.meta.url))]
        }],

        ['vite-plugin-checker', {
          vueTsc: false,
          OFF_eslint: {
            lintCommand: 'eslint -c ./eslint.config.js "./src*/**/*.{ts,js,mjs,cjs,vue}"',
            useFlatConfig: true
          }
        }, { server: false }]


      ]

      // polyfillModulePreload: true,

      // viteVuePluginOptions: {},

      // extractCSS: false,
      // transpile: false,

      // Add dependencies for transpiling with Babel (Array of string/regex)
      // (from node_modules, which are by default not transpiled).
      // Applies only if "transpile" is set to true.
      // transpileDependencies: [],

      // rtl: true, // https://v2.quasar.dev/options/rtl-supg
      // preloadChunks: true,
      // showProgress: false,
      // gzip: true,
      // analyze: true,

      // Options below are automatically set depending on the env, set them if you want to override
      // extractCSS: false,

      // https://v2.quasar.dev/quasar-cli/handling-webpack
      // "chain" is a webpack-chain object https://github.com/neutrinojs/webpack-chain
    },

    // Full list of options: https://v2.quasar.dev/quasar-cli/quasar-conf-js#Property%3A-devServer
    devServer: {
      https: {
        key: path.resolve(__dirname, 'localhost-key.pem'),
        cert: path.resolve(__dirname, 'localhost.pem'),
      },

      port: parseInt(process.env.PORT, 10),
      vueDevtools: false, // automatically opening remote Vue Devtools
      open: false, // opens browser window automatically
      hot: true, // Disable hot module replacement
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers': '*',
      },
    },

    // https://v2.quasar.dev/quasar-cli/quasar-conf-js#Property%3A-framework
    framework: {
      config: {},

      // iconSet: 'material-icons', // Quasar icon set
      // lang: 'en-US', // Quasar language pack

      // For special cases outside of where the auto-import strategy can have an impact
      // (like functional components as one of the examples),
      // you can manually specify Quasar components/directives to be available everywhere:
      //
      components: [
        'QLayout',
        'QDrawer',
        'QItemSection',
        'QHeader',
        'QFooter',
        'QPageContainer',
        'QPage',
        'QPopupProxy',
        'QToolbar',
        'QToolbarTitle',
        'QBtn',
        'QBtnDropdown',
        'QColor',
        'QIcon',
        'QList',
        'QKnob',
        'QItemLabel',
        'QItem',
        'QCard',
        'QMarkupTable',
        'QSpace',
        'QDialog',
        'QBadge',
        'QForm',
        'QCardSection',
        'QCardActions',
        'QField',
        'QInput',
        'QSelect',
        'QMenu',
        'QToggle',
        'QFab',
        'QInfiniteScroll',
        'QAjaxBar',
        'QChip',
        'QExpansionItem',
        'QCheckbox',
        'QBanner',
        'QInnerLoading',
        'QSpinnerGears',
        'QSpinnerDots',
        'QDate',
        'QTime',
        'QSlideTransition',
        'QTable',
        'QTh',
        'QTr',
        'QTd',
        'QLinearProgress',
        'QSlider',
        'QPopupEdit',
        'QCarousel',
        'QCarouselControl',
        'QCarouselSlide',
        'QPageScroller',
        'QAvatar',
        'QImg',
        'QSplitter',
        'QRating',
        'QParallax',
        'QTab',
        'QTabs',
        'QTabPanels',
        'QTabPanel',
        'QTree',
        'QSeparator',
      ],
      directives: [
        'Ripple',
        'ClosePopup',
      ],
      _plugins: [
        'Meta',
        'Dialog',
        'Notify',
        'Cookies',
        'Loading',
        'AppVisibility',
        'LocalStorage',
        'SessionStorage',
      ],
      get plugins_1() {
        return this._plugins;
      },
      set plugins_1(value) {
        this._plugins = value;
      },
      get plugins() {
        return this._plugins;
      },
      set plugins(value) {
        this._plugins = value;
      },
      iconSet: 'fontawesome-v5',
      lang: 'it', // Quasar language
    },

    animations: 'all', // --- includes all animations
    // https://v2.quasar.dev/options/animations
    // animations: [],

    // https://v2.quasar.dev/quasar-cli/developing-ssr/configuring-ssr
    ssr: {
      pwa: false,

      // manualStoreHydration: true,
      // manualPostHydrationTrigger: true,

      prodPort: 3000, // The default port that the production server should use
      // (gets superseded if import.meta.env.PORT is specified at runtime)

      maxAge: 1000 * 60 * 60 * 24 * 30,
      // Tell browser when a file from the server should expire from cache (in ms)


      middlewares: [
        ctx.prod ? 'compression' : '',
        'render', // keep this as last one
      ],
    },


    // https://v2.quasar.dev/quasar-cli/developing-pwa/configuring-pwa
    pwa: {
      workboxMode: 'InjectManifest', // 'GenerateSW' or 'InjectManifest'
      swFilename: 'sw-' + process.env.APP_VERSION + '.js',
      workboxOptions: {
        swSrc: 'src-pwa/custom-service-worker.js', // Assicurati che il file esista
        include: [/\.html$/, /\.js$/, /\.css$/, /\.png$/, /\.svg$/, /\.json$/], // File da precacheare
      },
      /*extendGenerateSWOptions(cfg) {
        cfg.skipWaiting = false
        cfg.clientsClaim = false
      },*/
    },

    sourceFiles: {
      pwaRegisterServiceWorker: 'src-pwa/register-service-worker',
      pwaServiceWorker: 'src-pwa/custom-service-worker',
      pwaManifestFile: 'src-pwa/manifest.json',
    },

    // Full list of options: https://v2.quasar.dev/quasar-cli/developing-cordova-apps/configuring-cordova
    cordova: {
      // noIosLegacyBuildFlag: true, // uncomment only if you know what you are doing
    },

    // Full list of options: https://v2.quasar.dev/quasar-cli/developing-capacitor-apps/configuring-capacitor
    capacitor: {
      hideSplashscreen: true,
    },

    // Full list of options: https://v2.quasar.dev/quasar-cli/developing-electron-apps/configuring-electron
    electron: {
      bundler: 'packager', // 'packager' or 'builder'

      packager: {
        // https://github.com/electron-userland/electron-packager/blob/master/docs/api.md#options

        // OS X / Mac App Store
        // appBundleId: '',
        // appCategoryType: '',
        // osxSign: '',
        // protocol: 'myapp://path',

        // Windows only
        // win32metadata: { ... }
      },

      builder: {
        // https://www.electron.build/configuration/configuration

        appId: '-',
      },


    },
  }
})
