import { defineConfig } from "eslint/config"
import baseConfig from "../../eslint.config.mjs"

// Create a deep copy of the base config to avoid mutation
const baseConfigArray = [...baseConfig]

// Find the TypeScript specific configuration to modify its rules
const tsConfigIndex = baseConfigArray.findIndex(
  (config) =>
    config.files?.includes("**/*.{ts,tsx}") &&
    config.plugins?.["@typescript-eslint"],
)

if (tsConfigIndex !== -1) {
  // Make a copy of the TS config to avoid direct mutation
  const tsConfig = { ...baseConfigArray[tsConfigIndex] }

  // Make a copy of the rules
  tsConfig.rules = {
    ...tsConfig.rules,
    // Override the no-unused-vars rule with backend-specific patterns
    "@typescript-eslint/no-unused-vars": [
      "error",
      {
        argsIgnorePattern:
          "^_|^fastify$|^app$|^request$|^response$|^req$|^res$|^reply$|^error$",
        varsIgnorePattern:
          "^_|^fastify$|^app$|^request$|^response$|^req$|^res$|^reply$|^error$",
      },
    ],
  }

  // Replace the original config with our modified one
  baseConfigArray[tsConfigIndex] = tsConfig
}

// Add backend-specific rules
const backendConfig = [
  ...baseConfigArray,
  {
    files: ["**/*.{js,mjs,cjs,ts}"],
    rules: {
      "no-process-exit": "error",
      "no-sync": "warn", // Warn about synchronous methods that can block the event loop
    },
  },
  {
    ignores: ["src/shared/**/*"],
  },
]

export default defineConfig(backendConfig)
