/**
 * AI Code Fingerprinting Test Fixtures
 * Tests for detecting AI-generated code patterns with security implications
 */

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

export const aiFingerprintingTests: TestGroup = {
  name: 'AI Code Fingerprinting',
  tier: 'B',
  layer: 2,
  description: 'Detection of AI-generated code patterns that may indicate security risks',

  truePositives: [
    {
      name: 'AI Fingerprinting - True Positives',
      expectFindings: true,
      expectedCategories: ['ai_pattern'],
      description: 'AI-generated code patterns that MUST be detected',
      file: {
        path: 'src/services/ai-service.ts',
        content: `
import { OpenAI } from 'openai'

// TODO: implement authentication - PLACEHOLDER
export async function processRequest(data: any) {
  // placeholder implementation
  return null
}

// AI hardcoded secret pattern - CRITICAL
const API_KEY = 'sk-1234567890abcdef'
const SECRET = 'super_secret_value_here'

// AI example credentials - HIGH
const admin_password = 'admin123'
const test_token = 'test-token-12345'

// AI permissive CORS - MEDIUM
app.use(cors())
response.setHeader('Access-Control-Allow-Origin', '*')

// AI disabled security for testing - MEDIUM
// disable for testing - auth bypass
// skip authentication temporarily
function skipAuth() {
  return true
}

// TODO: add security validation - LOW
// TODO: implement sanitization

// AI empty function body - LOW
function validateInput(input: string) {
  // stub implementation
}

const emptyHandler = () => {}

// AI console.log debugging - INFO
console.log('debug checking data here')
console.log('testing response:', result)

// AI boilerplate error message - INFO
throw new Error('Something went wrong')
throw new Error('An error occurred')
`,
        language: 'typescript',
        size: 900,
      },
    },
    {
      name: 'TypeScript Any at Security Boundaries',
      expectFindings: true,
      expectedCategories: ['ai_pattern'],
      description: 'TypeScript any usage at API/auth/database boundaries',
      file: {
        path: 'src/api/users/route.ts',
        content: `
import { NextResponse } from 'next/server'
import { db } from '@/lib/db'

// 'any' at API boundary - should be flagged
export async function POST(request: Request) {
  const body = await request.json() as any
  const { userId } = body

  // Using any for request params
  const params = req.params as any
  const query = req.query as any

  return NextResponse.json({ success: true })
}

// 'any' in auth context - should be flagged
export async function verifyToken(token: any) {
  const decoded = jwt.verify(token) as any
  const session: any = await getSession()
  const auth: any = checkAuth()

  return decoded.userId
}

// 'any' in database layer with raw query - should be flagged
export async function searchUsers(term: string) {
  const results: any = await db.execute(\`SELECT * FROM users WHERE name LIKE '%\${term}%'\`)
  return results.rows as any
}
`,
        language: 'typescript',
        size: 700,
      },
    },
    {
      name: 'Localhost URLs in Production Code',
      expectFindings: true,
      expectedCategories: ['ai_pattern'],
      description: 'Hardcoded localhost/example URLs that should be replaced',
      file: {
        path: 'src/lib/api-client.ts',
        content: `
// Hardcoded localhost URLs - should be flagged
const API_URL = 'http://localhost:3000/api'
const BACKEND = 'http://127.0.0.1:8080/graphql'
const EXAMPLE = 'https://example.com/api/v1'
const PLACEHOLDER = 'https://your-domain.com/webhook'
const API_EXAMPLE = 'https://api.example.com/v2'

export async function fetchData() {
  const response = await fetch('http://localhost:4000/data')
  return response.json()
}

export async function callAPI() {
  return fetch('https://example.com/api/endpoint')
}
`,
        language: 'typescript',
        size: 450,
      },
    },
  ],

  falseNegatives: [
    {
      name: 'AI Fingerprinting - False Negatives',
      expectFindings: false,
      description: 'Safe patterns that should NOT be flagged as AI fingerprints',
      allowedInfoFindings: [
        {
          category: 'ai_pattern',
          maxCount: 3,
          reason: 'Generic TODO comments and catch handlers are info-level, acceptable',
        },
        {
          category: 'dangerous_function',
          maxCount: 1,
          reason: 'JSON.parse with try-catch may generate info finding',
        },
      ],
      file: {
        path: 'src/utils/helpers.ts',
        content: `
// Normal TODO comments without security implications - SAFE
// TODO: refactor this function for better readability
// FIXME: improve performance of this loop

// TypeScript 'any' in safe contexts - SAFE

// Internal utility with 'any' (not at security boundary)
function formatData(items: any[]) {
  return items.map((item: any) => item.name)
}

// Type definition with 'any' - SAFE
type GenericResponse<T = any> = {
  data: T
  error?: string
}

// ORM/Database result mapping (safe internal use)
const users = results.map((row: any) => ({
  id: row.id,
  name: row.name,
}))

// Browser API event handler (incomplete typings) - SAFE
recognition.onresult = (event: any) => {
  const transcript = event.results[0][0].transcript
}

// Specific error handling (not catch-all) - SAFE
try {
  await fetchData()
} catch (error) {
  if (error instanceof NetworkError) {
    console.error('Network failed:', error.message)
  } else if (error instanceof ValidationError) {
    console.error('Validation failed:', error.details)
  }
}

// CORS with specific origins - SAFE
app.use(cors({
  origin: ['https://myapp.com', 'https://admin.myapp.com'],
  credentials: true,
}))

// Environment variable URLs (not hardcoded) - SAFE
const API_URL = process.env.API_URL || 'http://localhost:3000'
const BACKEND = process.env.BACKEND_URL
`,
        language: 'typescript',
        size: 1000,
      },
    },
    {
      name: 'Test File Patterns',
      expectFindings: false,
      description: 'AI patterns in test files should be downgraded/ignored',
      allowedInfoFindings: [
        {
          category: 'ai_pattern',
          maxCount: 5,
          reason: 'Test file patterns are downgraded to info level',
        },
        {
          category: 'hardcoded_secret',
          maxCount: 2,
          reason: 'Test credentials in test files may be detected at low severity',
        },
      ],
      file: {
        path: 'src/__tests__/auth.test.ts',
        content: `
import { describe, it, expect } from 'vitest'

// Test credentials - OK in test files
const TEST_API_KEY = 'test-key-12345'
const mock_password = 'test123'

describe('Auth', () => {
  it('should authenticate user', async () => {
    // TODO: add more test cases
    const result = await auth.login('test@example.com', 'password')
    expect(result).toBeDefined()
  })

  it('should handle errors', async () => {
    try {
      await auth.login('invalid', 'bad')
    } catch (error) {
      // Generic catch is OK in tests
      console.log('Expected error:', error)
      expect(error).toBeDefined()
    }
  })
})

// Mock implementation - OK in test files
function mockValidate(input: any) {
  // placeholder implementation for tests
  return true
}
`,
        language: 'typescript',
        size: 700,
      },
    },
    {
      name: 'Config File Patterns',
      expectFindings: false,
      description: 'Localhost URLs in config files should be OK (dev defaults)',
      allowedInfoFindings: [
        {
          category: 'ai_pattern',
          maxCount: 1,
          reason: 'Config files may have info-level patterns',
        },
        {
          category: 'sensitive_url',
          maxCount: 2,
          reason: 'Localhost URLs in config with env fallback are low severity',
        },
      ],
      file: {
        path: 'src/config/endpoints.ts',
        content: `
// Environment-based config with localhost fallbacks - SAFE
export const config = {
  apiUrl: process.env.API_URL || 'http://localhost:3000/api',
  graphqlEndpoint: process.env.GRAPHQL_URL || 'http://localhost:4000/graphql',
  wsEndpoint: process.env.WS_URL || 'ws://localhost:3000',
}

// Development defaults with clear documentation - SAFE
const DEFAULTS = {
  // Default to localhost for development
  backendUrl: 'http://localhost:8080',
  // These should be overridden in production via env vars
  redisUrl: 'redis://localhost:6379',
}

export function getApiUrl() {
  if (process.env.NODE_ENV === 'production') {
    return process.env.API_URL
  }
  return 'http://localhost:3000'  // OK in config with condition
}
`,
        language: 'typescript',
        size: 600,
      },
    },
  ],
}
