/**
 * Refactor Safety Snapshot Tests for dangerous-functions.ts
 *
 * These tests capture the current behavior of detectDangerousFunctions()
 * to ensure refactoring doesn't change any detection behavior.
 *
 * DO NOT modify these tests unless intentionally changing detection behavior.
 */

import { detectDangerousFunctions } from '../../detect/structural/dangerous-functions'

describe('Refactor Safety - dangerous-functions.ts', () => {
  describe('eval/Function detection', () => {
    it('should detect eval() usage', () => {
      const code = `
const result = eval(userInput);
const computed = eval('2 + 2');
`
      const result = detectDangerousFunctions(code, 'src/handler.ts')
      expect(result).toMatchSnapshot()
    })

    it('should detect Function constructor', () => {
      const code = `
const fn = new Function('a', 'b', 'return a + b');
const dynamic = new Function(userCode);
`
      const result = detectDangerousFunctions(code, 'src/handler.ts')
      expect(result).toMatchSnapshot()
    })

    it('should detect setTimeout/setInterval with string', () => {
      const code = `
setTimeout('alert("hello")', 1000);
setInterval('console.log("tick")', 500);
`
      const result = detectDangerousFunctions(code, 'src/handler.ts')
      expect(result).toMatchSnapshot()
    })
  })

  describe('child_process detection', () => {
    it('should detect exec with user input', () => {
      const code = `
import { exec } from 'child_process';
exec(\`ls \${userInput}\`, callback);
`
      const result = detectDangerousFunctions(code, 'src/handler.ts')
      expect(result).toMatchSnapshot()
    })

    it('should detect execSync with static command', () => {
      const code = `
const { execSync } = require('child_process');
const output = execSync('ls -la');
`
      const result = detectDangerousFunctions(code, 'src/handler.ts')
      expect(result).toMatchSnapshot()
    })

    it('should NOT flag RegExp.exec as child_process', () => {
      const code = `
const regex = /pattern/g;
const match = regex.exec(text);
`
      const result = detectDangerousFunctions(code, 'src/handler.ts')
      expect(result).toMatchSnapshot()
    })

    it('should detect spawn with dynamic args', () => {
      const code = `
import { spawn } from 'child_process';
spawn('node', [userInput]);
`
      const result = detectDangerousFunctions(code, 'src/handler.ts')
      expect(result).toMatchSnapshot()
    })
  })

  describe('SQL injection detection', () => {
    it('should detect raw SQL with template literal', () => {
      const code = `
const query = \`SELECT * FROM users WHERE id = \${userId}\`;
db.query(query);
`
      const result = detectDangerousFunctions(code, 'src/db.ts')
      expect(result).toMatchSnapshot()
    })

    it('should detect SQL string concatenation', () => {
      const code = `
const query = "SELECT * FROM users WHERE name = '" + userName + "'";
`
      const result = detectDangerousFunctions(code, 'src/db.ts')
      expect(result).toMatchSnapshot()
    })

    it('should detect SQL with whitelist validation as lower severity', () => {
      const code = `
const allowedColumns = ['name', 'email', 'age'];
if (!allowedColumns.includes(sortBy)) throw new Error('Invalid column');
const query = \`SELECT * FROM users ORDER BY \${sortBy}\`;
`
      const result = detectDangerousFunctions(code, 'src/db.ts')
      expect(result).toMatchSnapshot()
    })
  })

  describe('innerHTML/XSS detection', () => {
    it('should detect innerHTML with dynamic content', () => {
      const code = `
element.innerHTML = userContent;
div.innerHTML = \`<div>\${data}</div>\`;
`
      const result = detectDangerousFunctions(code, 'src/component.ts')
      expect(result).toMatchSnapshot()
    })

    it('should detect innerHTML with static content as lower severity', () => {
      const code = `
element.innerHTML = '<div class="container">Static content</div>';
`
      const result = detectDangerousFunctions(code, 'src/component.ts')
      expect(result).toMatchSnapshot()
    })

    it('should detect dangerouslySetInnerHTML', () => {
      const code = `
<div dangerouslySetInnerHTML={{ __html: userHtml }} />
`
      const result = detectDangerousFunctions(code, 'src/component.tsx')
      expect(result).toMatchSnapshot()
    })

    it('should detect innerHTML with DOMPurify as lower severity', () => {
      const code = `
import DOMPurify from 'dompurify';
const sanitized = DOMPurify.sanitize(userHtml);
element.innerHTML = sanitized;
`
      const result = detectDangerousFunctions(code, 'src/component.ts')
      expect(result).toMatchSnapshot()
    })

    it('should skip style element innerHTML', () => {
      const code = `
const styleElement = document.createElement('style');
styleElement.innerHTML = '.class { color: red; }';
`
      const result = detectDangerousFunctions(code, 'src/styles.ts')
      expect(result).toMatchSnapshot()
    })

    it('should detect document.write', () => {
      const code = `
document.write('<script>alert(1)</script>');
`
      const result = detectDangerousFunctions(code, 'src/legacy.ts')
      expect(result).toMatchSnapshot()
    })
  })

  describe('JSON.parse detection', () => {
    it('should detect JSON.parse on user input', () => {
      const code = `
const data = JSON.parse(req.body);
`
      const result = detectDangerousFunctions(code, 'src/api/handler.ts')
      expect(result).toMatchSnapshot()
    })

    it('should detect JSON.parse on localStorage', () => {
      const code = `
const settings = JSON.parse(localStorage.getItem('settings'));
`
      const result = detectDangerousFunctions(code, 'src/settings.ts')
      expect(result).toMatchSnapshot()
    })

    it('should suppress JSON.parse with try-catch on internal data', () => {
      const code = `
try {
  const config = JSON.parse(fileContent);
} catch (e) {
  console.error(e);
}
`
      const result = detectDangerousFunctions(code, 'src/config.ts')
      expect(result).toMatchSnapshot()
    })

    it('should detect JSON.parse with schema validation as handled', () => {
      const code = `
const raw = JSON.parse(input);
const validated = schema.parse(raw);
`
      const result = detectDangerousFunctions(code, 'src/api/handler.ts')
      expect(result).toMatchSnapshot()
    })

    it('should skip JSON.parse in test files', () => {
      const code = `
const mockData = JSON.parse(fixture);
`
      const result = detectDangerousFunctions(code, 'src/__tests__/handler.test.ts')
      expect(result).toMatchSnapshot()
    })

    it('should skip trusted SDK response parsing', () => {
      const code = `
const response = await openai.chat.completions.create({});
const content = JSON.parse(response.choices[0].content);
`
      const result = detectDangerousFunctions(code, 'src/ai/chat.ts')
      expect(result).toMatchSnapshot()
    })
  })

  describe('Math.random detection', () => {
    it('should detect Math.random for security tokens as high', () => {
      const code = `
function generateToken() {
  return Math.random().toString(36);
}
`
      const result = detectDangerousFunctions(code, 'src/auth.ts')
      expect(result).toMatchSnapshot()
    })

    it('should detect Math.random in security context as high', () => {
      const code = `
const secret = Math.random().toString(36).substring(2);
`
      const result = detectDangerousFunctions(code, 'src/crypto.ts')
      expect(result).toMatchSnapshot()
    })

    it('should classify Math.random for UI IDs as info', () => {
      const code = `
const key = Math.random().toString(36).substring(2, 9);
`
      const result = detectDangerousFunctions(code, 'src/components/list.tsx')
      expect(result).toMatchSnapshot()
    })

    it('should skip Math.random in seed files', () => {
      const code = `
const randomAge = Math.random() * 100;
`
      const result = detectDangerousFunctions(code, 'src/seed/users.ts')
      expect(result).toMatchSnapshot()
    })

    it('should skip cosmetic Math.random (CSS values)', () => {
      const code = `
const opacity = Math.random() * 0.5 + 0.5;
element.style.opacity = opacity;
`
      const result = detectDangerousFunctions(code, 'src/animation.ts')
      expect(result).toMatchSnapshot()
    })

    it('should classify business IDs as low severity', () => {
      const code = `
const orderId = 'ORD-' + Math.random().toString(36).substring(2, 12);
`
      const result = detectDangerousFunctions(code, 'src/orders.ts')
      expect(result).toMatchSnapshot()
    })
  })

  describe('File path detection', () => {
    it('should detect dynamic file path in API handlers', () => {
      const code = `
const file = fs.readFileSync(req.params.filename);
`
      const result = detectDangerousFunctions(code, 'src/api/files.ts')
      expect(result).toMatchSnapshot()
    })

    it('should detect path traversal risk', () => {
      const code = `
const fullPath = path.join(uploadDir, req.query.path);
`
      const result = detectDangerousFunctions(code, 'src/api/upload.ts')
      expect(result).toMatchSnapshot()
    })

    it('should skip dynamic paths in CLI tools', () => {
      const code = `
const content = fs.readFileSync(filePath);
`
      const result = detectDangerousFunctions(code, 'src/cli/scan.ts')
      expect(result).toMatchSnapshot()
    })

    it('should detect path traversal with sanitization as lower severity', () => {
      const code = `
if (filename.includes('..')) throw new Error('Invalid path');
const fullPath = path.resolve(baseDir, filename);
if (!fullPath.startsWith(baseDir)) throw new Error('Access denied');
fs.readFileSync(fullPath);
`
      const result = detectDangerousFunctions(code, 'src/api/files.ts')
      expect(result).toMatchSnapshot()
    })
  })

  describe('request.json() validation detection', () => {
    it('should suggest schema validation for request.json()', () => {
      const code = `
export async function POST(request: Request) {
  const body = await request.json();
  return Response.json({ ok: true });
}
`
      const result = detectDangerousFunctions(code, 'src/app/api/create/route.ts')
      expect(result).toMatchSnapshot()
    })

    it('should skip when schema validation is present', () => {
      const code = `
import { z } from 'zod';
const schema = z.object({ name: z.string() });

export async function POST(request: Request) {
  const body = await request.json();
  const data = schema.parse(body);
  return Response.json({ data });
}
`
      const result = detectDangerousFunctions(code, 'src/app/api/create/route.ts')
      expect(result).toMatchSnapshot()
    })

    it('should skip when throwing auth helper is present', () => {
      const code = `
export async function POST(request: Request) {
  const userId = await getCurrentUserId();
  const body = await request.json();
  return Response.json({ ok: true });
}
`
      const result = detectDangerousFunctions(code, 'src/app/api/create/route.ts')
      expect(result).toMatchSnapshot()
    })
  })

  describe('Deserialization detection', () => {
    it('should detect pickle.loads (Python)', () => {
      const code = `
data = pickle.loads(user_data)
`
      const result = detectDangerousFunctions(code, 'handler.py')
      expect(result).toMatchSnapshot()
    })

    it('should detect yaml.load without safe loader', () => {
      const code = `
config = yaml.load(file_content)
`
      const result = detectDangerousFunctions(code, 'config.py')
      expect(result).toMatchSnapshot()
    })
  })

  describe('Prototype pollution detection', () => {
    it('should detect Object.assign with user input', () => {
      const code = `
const merged = Object.assign({}, req.body);
`
      const result = detectDangerousFunctions(code, 'src/api/merge.ts')
      expect(result).toMatchSnapshot()
    })

    it('should detect spread operator with user input', () => {
      const code = `
const user = { ...req.body, createdAt: new Date() };
`
      const result = detectDangerousFunctions(code, 'src/api/create.ts')
      expect(result).toMatchSnapshot()
    })
  })

  describe('Regex DoS detection', () => {
    it('should detect dynamic regex construction', () => {
      const code = `
const pattern = new RegExp(userPattern);
`
      const result = detectDangerousFunctions(code, 'src/search.ts')
      expect(result).toMatchSnapshot()
    })
  })

  describe('Test file handling', () => {
    it('should downgrade severity in test files', () => {
      const code = `
eval(testCode);
element.innerHTML = testHtml;
`
      const result = detectDangerousFunctions(code, 'src/__tests__/handler.test.ts')
      expect(result).toMatchSnapshot()
    })

    it('should skip eval entirely in test files', () => {
      const code = `
it('should handle eval', () => {
  expect(eval('2 + 2')).toBe(4);
});
`
      const result = detectDangerousFunctions(code, 'src/__tests__/eval.test.ts')
      expect(result).toMatchSnapshot()
    })
  })

  describe('LLM prompt context detection', () => {
    it('should detect LLM prompt injection risk instead of XSS', () => {
      const code = `
const prompt = \`Answer this: \${userQuestion}\`;
const response = await openai.chat.completions.create({
  messages: [{ role: 'user', content: prompt }]
});
`
      const result = detectDangerousFunctions(code, 'src/ai/chat.ts')
      expect(result).toMatchSnapshot()
    })
  })

  describe('Static bootstrap script detection', () => {
    it('should detect static bootstrap as lower severity', () => {
      const code = `
const theme = localStorage.getItem('theme');
document.documentElement.setAttribute('data-theme', theme || 'light');
`
      const result = detectDangerousFunctions(code, 'src/bootstrap.ts')
      expect(result).toMatchSnapshot()
    })
  })
})
