/**
 * Express Framework Security Model
 *
 * res.json() auto-serialises (no XSS in JSON). Helmet adds security headers.
 * Template literals in res.send() with user data are XSS risks.
 */

import type { FrameworkSecurityModel } from './types'

const RES_JSON_RE = /res\.json\s*\(/
const RES_SEND_TEMPLATE_RE = /res\.send\s*\(\s*`/
const RES_SEND_CONCAT_RE = /res\.send\s*\([^)]*\+/
const RES_END_TEMPLATE_RE = /res\.end\s*\(\s*`/
const HELMET_RE = /helmet\s*\(/

export const expressModel: FrameworkSecurityModel = {
  framework: 'express',

  safePatterns: [
    {
      id: 'express_res_json_safe',
      suppressesCategory: ['xss'],
      detect: (line: string, _filePath: string, _fileContent: string) => RES_JSON_RE.test(line),
      reason: 'Express res.json() auto-serialises to JSON — no XSS risk in JSON responses',
    },
    {
      id: 'express_helmet_headers',
      suppressesCategory: ['insecure_config', 'cors_misconfiguration'],
      detect: (line: string, _filePath: string, _fileContent: string) => HELMET_RE.test(line),
      reason: 'Helmet middleware sets security headers by default',
    },
  ],

  unsafePatterns: [
    {
      id: 'express_res_send_template',
      boostsCategory: ['xss'],
      detect: (line: string, _filePath: string, _fileContent: string) => RES_SEND_TEMPLATE_RE.test(line),
      reason: 'Template literal in res.send() may include user data — XSS risk',
    },
    {
      id: 'express_res_send_concat',
      boostsCategory: ['xss'],
      detect: (line: string, _filePath: string, _fileContent: string) => RES_SEND_CONCAT_RE.test(line),
      reason: 'String concatenation in res.send() may include user data — XSS risk',
    },
    {
      id: 'express_res_end_template',
      boostsCategory: ['xss'],
      detect: (line: string, _filePath: string, _fileContent: string) => RES_END_TEMPLATE_RE.test(line),
      reason: 'Template literal in res.end() may include user data — XSS risk',
    },
  ],
}
