/**
 * Logic Gates Test Fixtures
 * Tests for detecting security bypass patterns and dangerous logic flows
 */

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

export const logicGatesTests: TestGroup = {
  name: 'Logic Gates / Security Bypass',
  tier: 'C',
  layer: 2,
  description: 'Detection of security bypass patterns, debug flags, and dangerous logic flows',

  truePositives: [
    {
      name: 'Security Bypass - True Positives',
      expectFindings: true,
      expectedCategories: ['security_bypass'],
      description: 'Security bypass patterns that MUST be detected',
      file: {
        path: 'src/middleware/auth.ts',
        content: `
import { NextRequest, NextResponse } from 'next/server'

// Development mode security bypass - HIGH
export function authMiddleware(req: NextRequest) {
  if (process.env.NODE_ENV !== 'production') return true
  if (process.env.NODE_ENV === 'development') {
    return NextResponse.next()
  }

  // Auth bypass with hardcoded true - CRITICAL
  if (true) {
    return NextResponse.next()
  }

  // Debug bypass flags - HIGH
  if (DEBUG) {
    return NextResponse.next()
  }
  if (SKIP_AUTH) {
    return true
  }
  if (BYPASS) {
    return allow()
  }

  return verifyAuth(req)
}

// Commented auth check - HIGH
export async function handler(req: Request) {
  // if (!user) return unauthorized
  // await verifyToken(token)
  // check permission before proceeding
  return processRequest(req)
}

// Validation skip patterns - HIGH
const config = {
  skipValidation: true,
  validate: false,
  noValidate: true,
}

// Disabled CSRF protection - HIGH
const securityOptions = {
  csrf: false,
  csrfProtection: false,
}

// Disabled SSL verification - CRITICAL
const httpsOptions = {
  rejectUnauthorized: false,
  verify: false,
  ssl: false,
}
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'

// Unsafe default allow - MEDIUM
function checkPermission(role: string) {
  switch (role) {
    case 'admin': return true
    case 'user': return limited()
    default: return true  // Unsafe!
  }
}

// Empty error handler - MEDIUM
try {
  await riskyOperation()
} catch (e) {
  // silently ignore
}

try {
  await anotherOperation()
} catch (error) {}

// Open redirect vulnerability - HIGH
app.get('/redirect', (req, res) => {
  redirect(req.query.url)
  redirect(req.params.destination)
  redirect(request.body.redirectUrl)
})

// Timing attack vulnerable comparison - MEDIUM
function verifySecret(input: string) {
  if (input === 'super-secret-value-12345678')
  if (token === userToken)
  if (password === storedPassword)
  if (secret === expectedSecret)
}

// Admin bypass pattern - MEDIUM
function checkAccess(user: User) {
  if (isAdmin) return true
  if (isSuperUser) continue
  if (role === 'admin') return
}
`,
        language: 'typescript',
        size: 1800,
      },
    },
  ],

  falseNegatives: [
    {
      name: 'Security Bypass - False Negatives',
      expectFindings: false,
      description: 'Safe patterns that should NOT be flagged as security bypasses',
      allowedInfoFindings: [
        {
          category: 'security_bypass',
          maxCount: 5,
          reason: 'Development mode checks may still generate low-severity findings',
        },
        {
          category: 'ai_pattern',
          maxCount: 3,
          reason: 'Catch blocks and feature flags may trigger ai-fingerprinting at info level',
        },
        {
          category: 'insecure_config',
          maxCount: 2,
          reason: 'Config patterns may trigger config detection',
        },
        {
          category: 'data_exposure',
          maxCount: 2,
          reason: 'Error handling patterns may trigger data exposure detection',
        },
        {
          category: 'dangerous_function',
          maxCount: 2,
          reason: 'URL operations may trigger dangerous function detection',
        },
      ],
      file: {
        path: 'src/middleware/safe-auth.ts',
        content: `
import { NextRequest, NextResponse } from 'next/server'
import crypto from 'crypto'

// Auth middleware with proper checks - SAFE
export function authMiddleware(req: NextRequest) {
  const token = req.headers.get('authorization')
  if (!token) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }
  return NextResponse.next()
}

// Proper error handling - SAFE
try {
  await riskyOperation()
} catch (error) {
  console.error('Operation failed:', error)
  throw new Error('Operation failed')
}

// Proper secret comparison using timing-safe - SAFE
function verifySecret(input: string, expected: string) {
  const inputBuffer = Buffer.from(input)
  const expectedBuffer = Buffer.from(expected)
  return crypto.timingSafeEqual(inputBuffer, expectedBuffer)
}

// Default deny pattern - SAFE
function checkPermission(role: string) {
  switch (role) {
    case 'admin': return true
    case 'user': return limited()
    default: return false  // Safe default deny
  }
}
`,
        language: 'typescript',
        size: 700,
      },
    },
    {
      name: 'Test File Patterns',
      expectFindings: false,
      description: 'Security bypass patterns in test files are expected',
      allowedInfoFindings: [
        {
          category: 'security_bypass',
          maxCount: 8,
          reason: 'Test files intentionally have bypass patterns for testing',
        },
        {
          category: 'insecure_config',
          maxCount: 3,
          reason: 'Test configs may trigger config detection',
        },
        {
          category: 'ai_pattern',
          maxCount: 2,
          reason: 'Test patterns may trigger AI detection',
        },
      ],
      file: {
        path: 'src/__tests__/auth.test.ts',
        content: `
import { describe, it, expect, vi } from 'vitest'

describe('Auth middleware', () => {
  it('should authenticate valid users', () => {
    const result = authenticate({ token: 'valid' })
    expect(result.authenticated).toBe(true)
  })

  it('should reject invalid users', () => {
    const result = authenticate({ token: 'invalid' })
    expect(result.authenticated).toBe(false)
  })
})
`,
        language: 'typescript',
        size: 300,
      },
    },
  ],
}
