/**
 * Framework-Specific Checks Test Fixtures
 * Tests for detecting framework-specific security issues
 */

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

export const frameworkChecksTests: TestGroup = {
  name: 'Framework-Specific Security',
  tier: 'C',
  layer: 2,
  description: 'Detection of framework-specific security issues (Next.js, Express, React, Django, Flask)',

  truePositives: [
    {
      name: 'Next.js Security Issues',
      expectFindings: true,
      expectedCategories: ['insecure_config'],
      description: 'Next.js specific security issues that MUST be detected',
      file: {
        path: 'src/app/api/data/route.ts',
        content: `
import { NextResponse } from 'next/server'
import { redirect, revalidatePath } from 'next/navigation'

// Next.js API route handler without auth check - MEDIUM
export default async function handler(req: any, res: any) {
  const data = await fetchSensitiveData()
  return res.json(data)
}

// Server action publicly accessible - MEDIUM
'use server';
export async function submitForm(data: FormData) {
  await db.insert(data)
}

// revalidatePath with user input - HIGH
export async function updateCache(request: Request) {
  const { path } = await request.json()
  revalidatePath(request.url)
  revalidatePath(params.path)
}

// redirect with user input - HIGH
export async function handleLogin(searchParams: { redirect: string }) {
  redirect(searchParams.redirect)
  redirect(url.pathname)
  redirect(request.nextUrl.pathname)
}

// getServerSideProps without auth - LOW
export async function getServerSideProps(context: any) {
  const data = await fetchData()
  return { props: { data } }
}

// unstable_cache without tags
import { unstable_cache } from 'next/cache'
const getCachedData = unstable_cache(async () => {
  return fetchData()
})
`,
        language: 'typescript',
        size: 900,
      },
    },
    {
      name: 'Express Security Issues',
      expectFindings: true,
      expectedCategories: ['insecure_config'],
      description: 'Express specific security issues that MUST be detected',
      file: {
        path: 'src/server/app.ts',
        content: `
import express from 'express'
import cors from 'cors'
import bodyParser from 'body-parser'

const app = express()

// Express without helmet - MEDIUM
const server = express()
// No helmet middleware added

// CORS allow all origins - HIGH
app.use(cors({
  origin: '*',
  credentials: true,
}))

// Body parser without limit - LOW
app.use(bodyParser.json())
app.use(bodyParser.urlencoded())

// Trust proxy without verification - MEDIUM
app.set('trust proxy', true)

// Error handler exposes stack - HIGH
app.use((err, req, res, next) => {
  res.json({
    error: err.message,
    stack: err.stack,  // Stack trace exposed!
  })
})

// Another stack exposure pattern
app.get('/error', (req, res) => {
  try {
    throw new Error('Oops')
  } catch (err) {
    res.send({ stack: err.stack })
  }
})
`,
        language: 'typescript',
        size: 700,
      },
    },
    {
      name: 'React Security Issues',
      expectFindings: true,
      expectedCategories: ['insecure_config'],
      description: 'React specific security issues that MUST be detected',
      file: {
        path: 'src/components/Form.tsx',
        content: `
import { useState, useEffect } from 'react'

// useEffect with async (memory leak) - LOW
function Component() {
  useEffect(async () => {
    const data = await fetchData()
    setData(data)
  }, [])

  // State with sensitive data - MEDIUM
  const [password, setPassword] = useState('initial-password')
  const [secret, setSecret] = useState('')
  const [token, setToken] = useState('')
  const [apiKey, setApiKey] = useState('')
  const [api_key, setApiKey2] = useState('')

  // href javascript: XSS - HIGH
  return (
    <div>
      <a href="javascript:alert('xss')">Click me</a>
      <a href='javascript:void(0)'>Another</a>
    </div>
  )
}

// Uncontrolled input with sensitive defaultValue - MEDIUM
function LoginForm({ savedPassword }) {
  return (
    <input
      type="password"
      defaultValue={password}
    />
  )
}

function TokenForm({ savedToken }) {
  return <input defaultValue={token} />
}
`,
        language: 'typescript',
        size: 750,
      },
    },
    {
      name: 'Django/Flask Security Issues',
      expectFindings: true,
      expectedCategories: ['insecure_config'],
      description: 'Python framework security issues that MUST be detected',
      file: {
        path: 'src/settings.py',
        content: `
from django.conf import settings

# Django DEBUG in production - CRITICAL
DEBUG = True

# ALLOWED_HOSTS wildcard - HIGH
ALLOWED_HOSTS = ['*']

# Django SECRET_KEY hardcoded - CRITICAL
SECRET_KEY = 'django-insecure-abc123def456ghi789jkl'

# ========== Flask patterns ==========

from flask import Flask

app = Flask(__name__)

# Flask debug mode - CRITICAL
app.run(debug=True, host='0.0.0.0')

# Flask secret key hardcoded - CRITICAL
app.secret_key = 'super-secret-flask-key'
`,
        language: 'python',
        size: 500,
      },
    },
  ],

  falseNegatives: [
    {
      name: 'Framework Checks - False Negatives',
      expectFindings: false,
      description: 'Safe framework patterns that should NOT be flagged',
      allowedInfoFindings: [
        {
          category: 'insecure_config',
          maxCount: 2,
          reason: 'Some framework patterns may still generate low-severity findings',
        },
        {
          category: 'ai_pattern',
          maxCount: 2,
          reason: 'Framework patterns may trigger AI detection',
        },
        {
          category: 'data_exposure',
          maxCount: 2,
          reason: 'Error handling patterns may trigger data exposure detection',
        },
        {
          category: 'sensitive_url',
          maxCount: 2,
          reason: 'URLs in CORS config may trigger URL detection',
        },
      ],
      file: {
        path: 'src/config/server-config.ts',
        content: `
// Server configuration with proper defaults - SAFE
export const serverConfig = {
  port: process.env.PORT || 3000,
  host: process.env.HOST || 'localhost',
  bodyLimit: '100kb',
}
`,
        language: 'typescript',
        size: 150,
      },
    },
    {
      name: 'Safe Python Framework Patterns',
      expectFindings: false,
      description: 'Safe Django/Flask patterns that should NOT be flagged',
      allowedInfoFindings: [
        {
          category: 'insecure_config',
          maxCount: 2,
          reason: 'Environment checks may still generate low-severity findings',
        },
        {
          category: 'sensitive_variable',
          maxCount: 2,
          reason: 'Variable names like SECRET_KEY may trigger sensitive variable detection',
        },
      ],
      file: {
        path: 'src/safe_settings.py',
        content: `
import os
from django.conf import settings

# DEBUG from environment - SAFE
DEBUG = os.environ.get('DEBUG', 'False') == 'True'

# ALLOWED_HOSTS from environment - SAFE
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '').split(',')

# SECRET_KEY from environment - SAFE
SECRET_KEY = os.environ.get('SECRET_KEY')
SECRET_KEY = os.getenv('DJANGO_SECRET_KEY')

# ========== Safe Flask patterns ==========

from flask import Flask

app = Flask(__name__)

# Debug from environment - SAFE
app.run(debug=os.environ.get('FLASK_DEBUG') == 'true')

# Secret key from environment - SAFE
app.secret_key = os.environ.get('SECRET_KEY')
app.config['SECRET_KEY'] = os.getenv('FLASK_SECRET')
`,
        language: 'python',
        size: 500,
      },
    },
    {
      name: 'Safe React Patterns',
      expectFindings: false,
      description: 'Safe React patterns that should NOT be flagged',
      allowedInfoFindings: [
        {
          category: 'insecure_config',
          maxCount: 1,
          reason: 'Some patterns may generate info findings',
        },
        {
          category: 'sensitive_url',
          maxCount: 2,
          reason: 'URLs in href may trigger URL detection',
        },
        {
          category: 'sensitive_variable',
          maxCount: 2,
          reason: 'Variable names like password may trigger sensitive variable detection',
        },
      ],
      file: {
        path: 'src/components/SafeForm.tsx',
        content: `
import { useState, useEffect } from 'react'

// Proper useEffect with async - SAFE
function Component() {
  useEffect(() => {
    loadData()
  }, [])

  // Non-sensitive state - SAFE
  const [name, setName] = useState('')

  return (
    <div>
      <a href="/dashboard">Dashboard</a>
      <button onClick={handleClick}>Click</button>
    </div>
  )
}
`,
        language: 'typescript',
        size: 300,
      },
    },
  ],
}
