/* eslint-disable operator-linebreak */
/* eslint-disable @typescript-eslint/no-var-requires */
const { withPlugins } = require('next-composed-plugins');
const withLess = require('next-with-less');
const withGraphQL = require('next-plugin-graphql');
const fs = require('fs');
const { COLORS_DEV, COLORS_PROD } = require('./constants/colors');
const envSchema = require('./config/schema/env');
const urls = require('./constants/urls');
const { devices } = require('./@packages/ui/screens');
const { publicRuntimeConfigSchema } = require('./config/schema/runtime-config');
const { serverRuntimeConfigSchema } = require('./config/schema/runtime-config');

const env = envSchema.parse(process.env);

const favicons = fs.readdirSync('./public/favicon/prod');
const faviconSubPath = env.USE_DEV_COLORS ? '/favicon/dev' : '/favicon/prod';
function buildFaviconRewrite(source) {
  return {
    source,
    destination: String.prototype.concat(faviconSubPath, source),
  };
}

/** @type {import('next').NextConfig} */
const nextConfig = {
  basePath: env.BASE_PATH,
  output: 'standalone',
  swcMinify: true,
  reactStrictMode: true,
  eslint: {
    ignoreDuringBuilds: true,
  },
  compiler: {
    styledComponents: true,
  },
  images: {
    deviceSizes: devices,
  },
  async rewrites() {
    return [
      {
        source: urls.URL_CRM_GRAPHQL_PROXY,
        destination: env.URL_CRM_GRAPHQL_DIRECT,
      },
      {
        source: urls.URL_GET_USER_PROXY,
        destination: env.URL_GET_USER_DIRECT,
      },
      {
        source: urls.URL_CORE_FINGAP_PROXY,
        destination: env.URL_CORE_FINGAP_DIRECT,
      },
      ...favicons.map((fileName) => buildFaviconRewrite(`/${fileName}`)),
    ];
  },
  publicRuntimeConfig: publicRuntimeConfigSchema.parse(env),
  serverRuntimeConfig: serverRuntimeConfigSchema.parse(env),
};

const plugins = [withLess, withGraphQL];

const colorPrimary = env.USE_DEV_COLORS ? COLORS_DEV.COLOR_PRIMARY : COLORS_PROD.COLOR_PRIMARY;

const config = {
  ...nextConfig,
  lessLoaderOptions: {
    lessOptions: {
      modifyVars: {
        'primary-color': colorPrimary,
      },
    },
  },
};

module.exports = withPlugins(config, plugins);
