/**
 * Configuration Audit Test Fixtures
 * Tests for detecting security misconfigurations in config files
 */

import type { TestGroup } from '../../types'

export const configAuditTests: TestGroup = {
  name: 'Configuration Auditing',
  tier: 'B',
  layer: 1,
  description: 'Detection of security misconfigurations in Dockerfile, CORS, Next.js, and package.json',

  truePositives: [
    {
      name: 'Dockerfile Security Issues',
      expectFindings: true,
      expectedCategories: ['insecure_config'],
      description: 'Dockerfile misconfigurations that MUST be detected',
      file: {
        path: 'Dockerfile',
        content: `
FROM node:18-alpine

WORKDIR /app

COPY package*.json ./
RUN npm install

COPY . .

# Explicitly running as root - HIGH
USER root

# Hardcoded secrets in build args - CRITICAL
ARG DATABASE_PASSWORD=supersecret123
ARG API_SECRET_KEY=sk-live-abc123
ENV JWT_SECRET=my-jwt-signing-key
ENV DB_PASSWORD=production-db-pass

EXPOSE 3000

CMD ["npm", "start"]
`,
        language: 'dockerfile',
        size: 350,
      },
    },
    {
      name: 'Permissive CORS Configuration',
      expectFindings: true,
      expectedCategories: ['insecure_config'],
      description: 'Wildcard CORS that MUST be detected',
      file: {
        path: 'src/server/cors.ts',
        content: `
import express from 'express'
import cors from 'cors'

const app = express()

// Permissive CORS - MEDIUM
app.use(cors({
  origin: '*',
  credentials: true,
}))

// Another pattern - MEDIUM
const headers = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
}

// Config object pattern - MEDIUM
const corsConfig = {
  allowedOrigins: ['*'],
  origin: '*',
}

// In response header
res.setHeader('Access-Control-Allow-Origin', '*')
`,
        language: 'typescript',
        size: 450,
      },
    },
    {
      name: 'Next.js Security Config',
      expectFindings: true,
      expectedCategories: ['insecure_config'],
      description: 'Next.js security misconfigurations that MUST be detected',
      file: {
        path: 'next.config.js',
        content: `
/** @type {import('next').NextConfig} */
const nextConfig = {
  // Exposing X-Powered-By header - LOW
  poweredByHeader: true,

  // Exposing source maps in production - MEDIUM
  productionBrowserSourceMaps: true,

  // Other config
  reactStrictMode: true,
  images: {
    domains: ['cdn.example.com'],
  },
}

module.exports = nextConfig
`,
        language: 'javascript',
        size: 300,
      },
    },
    {
      name: 'Package.json Security Issues',
      expectFindings: true,
      expectedCategories: ['insecure_config'],
      description: 'Package.json security issues that MUST be detected',
      file: {
        path: 'package.json',
        content: `{
  "name": "my-app",
  "version": "1.0.0",
  "scripts": {
    "start": "node index.js",
    "postinstall": "node scripts/setup.js",
    "preinstall": "node scripts/verify.js"
  },
  "dependencies": {
    "express": "*",
    "lodash": "latest",
    "axios": "^1.0.0"
  },
  "devDependencies": {
    "jest": "*"
  }
}`,
        language: 'json',
        size: 350,
      },
    },
    {
      name: 'Dockerfile Without USER',
      expectFindings: true,
      expectedCategories: ['insecure_config'],
      description: 'Dockerfile without USER instruction runs as root by default',
      file: {
        path: 'services/api/Dockerfile',
        content: `
FROM python:3.11-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .

EXPOSE 8000

# No USER instruction - runs as root by default - MEDIUM
CMD ["python", "app.py"]
`,
        language: 'dockerfile',
        size: 200,
      },
    },
  ],

  falseNegatives: [
    {
      name: 'Safe Dockerfile Configuration',
      expectFindings: false,
      description: 'Properly configured Dockerfile that should NOT be flagged',
      allowedInfoFindings: [
        {
          category: 'insecure_config',
          maxCount: 1,
          reason: 'Some patterns may generate low-severity findings',
        },
      ],
      file: {
        path: 'Dockerfile',
        content: `
FROM node:18-alpine

WORKDIR /app

COPY package*.json ./
RUN npm install --production

COPY . .

# Running as non-root user - SAFE
USER node

# Secrets from build args without defaults - SAFE
ARG DATABASE_URL
ENV DATABASE_URL=\${DATABASE_URL}

EXPOSE 3000

CMD ["npm", "start"]
`,
        language: 'dockerfile',
        size: 250,
      },
    },
    {
      name: 'Safe Docker Compose',
      expectFindings: false,
      description: 'Docker Compose with secrets from env vars should NOT be flagged',
      file: {
        path: 'docker-compose.yml',
        content: `
version: '3.8'

services:
  app:
    build: .
    ports:
      - "3000:3000"
    environment:
      # Secrets from environment variables - SAFE
      DATABASE_PASSWORD: \${DATABASE_PASSWORD}
      API_KEY: \${API_KEY}
      JWT_SECRET: \${JWT_SECRET}
    env_file:
      - .env

  db:
    image: postgres:15
    environment:
      POSTGRES_PASSWORD: \${POSTGRES_PASSWORD}
`,
        language: 'yaml',
        size: 350,
      },
    },
    {
      name: 'Safe CORS Configuration',
      expectFindings: false,
      description: 'Properly configured CORS should NOT be flagged',
      allowedInfoFindings: [
        {
          category: 'insecure_config',
          maxCount: 1,
          reason: 'CORS patterns may generate low-severity findings',
        },
        {
          category: 'sensitive_url',
          maxCount: 2,
          reason: 'URLs in CORS config may trigger URL detection',
        },
        {
          category: 'ai_pattern',
          maxCount: 1,
          reason: 'Function-based patterns may trigger AI detection',
        },
      ],
      file: {
        path: 'src/config/cors-config.ts',
        content: `
// Environment-based CORS configuration - SAFE
export const corsConfig = {
  origin: process.env.ALLOWED_ORIGINS?.split(','),
  credentials: true,
}
`,
        language: 'typescript',
        size: 100,
      },
    },
    {
      name: 'Safe Next.js Config',
      expectFindings: false,
      description: 'Secure Next.js configuration should NOT be flagged',
      file: {
        path: 'next.config.js',
        content: `
/** @type {import('next').NextConfig} */
const nextConfig = {
  // Disabled header - SAFE (or omitted entirely)
  poweredByHeader: false,

  // Source maps disabled - SAFE
  productionBrowserSourceMaps: false,

  reactStrictMode: true,

  // Security headers
  async headers() {
    return [
      {
        source: '/:path*',
        headers: [
          { key: 'X-Frame-Options', value: 'DENY' },
          { key: 'X-Content-Type-Options', value: 'nosniff' },
        ],
      },
    ]
  },
}

module.exports = nextConfig
`,
        language: 'javascript',
        size: 400,
      },
    },
    {
      name: 'Safe Package.json',
      expectFindings: false,
      description: 'Properly configured package.json should NOT be flagged',
      file: {
        path: 'package.json',
        content: `{
  "name": "my-app",
  "version": "1.0.0",
  "scripts": {
    "start": "node index.js",
    "build": "tsc",
    "test": "jest"
  },
  "dependencies": {
    "express": "^4.18.2",
    "lodash": "^4.17.21",
    "axios": "~1.6.0"
  },
  "devDependencies": {
    "jest": "^29.7.0",
    "typescript": "^5.3.0"
  }
}`,
        language: 'json',
        size: 300,
      },
    },
    {
      name: 'Example/Template Configs',
      expectFindings: false,
      description: 'Example configs with placeholders should NOT be flagged',
      file: {
        path: 'docker-compose.example.yml',
        content: `
version: '3.8'

services:
  app:
    build: .
    environment:
      # Replace with your actual values
      DATABASE_PASSWORD: <YOUR_PASSWORD_HERE>
      API_KEY: your-api-key-here
      JWT_SECRET: CHANGEME
`,
        language: 'yaml',
        size: 200,
      },
    },
  ],
}
