export const nginxSchema = {
  id: 'nginx',
  name: 'NGINX',
  icon: 'Monitor',
  category: '代理与Web',
  description: '高性能 HTTP 和反向代理服务器',
  format: 'conf',
  fileName: 'nginx.conf',
  groups: [
    {
      title: '基础配置',
      fields: [
        {
          key: 'workerProcesses',
          label: 'Worker 进程数',
          type: 'select',
          options: [
            { label: 'auto (自动检测)', value: 'auto' },
            { label: '1', value: '1' },
            { label: '2', value: '2' },
            { label: '4', value: '4' },
            { label: '8', value: '8' },
          ],
          default: 'auto',
          tip: '通常设置为 CPU 核心数',
        },
        {
          key: 'workerConnections',
          label: '单 Worker 最大连接数',
          type: 'number',
          min: 512,
          max: 65535,
          step: 512,
          default: 1024,
          tip: '每个 Worker 进程能处理的最大并发连接数',
        },
      ],
    },
    {
      title: 'HTTP 服务',
      fields: [
        {
          key: 'httpPort',
          label: 'HTTP 端口',
          type: 'number',
          min: 1,
          max: 65535,
          default: 80,
        },
        {
          key: 'serverName',
          label: '域名 (server_name)',
          type: 'text',
          placeholder: 'example.com',
          default: 'localhost',
          required: true,
          tip: '支持通配符，如 *.example.com',
        },
        {
          key: 'enableGzip',
          label: '开启 Gzip 压缩',
          type: 'switch',
          default: true,
          tip: '压缩响应体，减少传输体积',
        },
        {
          key: 'gzipTypes',
          label: 'Gzip 压缩类型',
          type: 'text',
          default: 'text/plain text/css application/json application/javascript text/xml',
          dependsOn: { key: 'enableGzip', value: true },
          tip: 'MIME 类型，空格分隔',
        },
      ],
    },
    {
      title: 'HTTPS / SSL',
      fields: [
        {
          key: 'enableHttps',
          label: '开启 HTTPS',
          type: 'switch',
          default: false,
        },
        {
          key: 'httpsPort',
          label: 'HTTPS 端口',
          type: 'number',
          min: 1,
          max: 65535,
          default: 443,
          dependsOn: { key: 'enableHttps', value: true },
        },
        {
          key: 'sslCertificate',
          label: 'SSL 证书路径',
          type: 'text',
          placeholder: '/etc/nginx/ssl/cert.pem',
          default: '/etc/nginx/ssl/cert.pem',
          dependsOn: { key: 'enableHttps', value: true },
          required: true,
        },
        {
          key: 'sslCertificateKey',
          label: 'SSL 私钥路径',
          type: 'text',
          placeholder: '/etc/nginx/ssl/key.pem',
          default: '/etc/nginx/ssl/key.pem',
          dependsOn: { key: 'enableHttps', value: true },
          required: true,
        },
        {
          key: 'sslProtocols',
          label: 'TLS 版本',
          type: 'select',
          options: [
            { label: 'TLSv1.2 + TLSv1.3 (推荐)', value: 'TLSv1.2 TLSv1.3' },
            { label: 'TLSv1.1 + TLSv1.2 + TLSv1.3', value: 'TLSv1.1 TLSv1.2 TLSv1.3' },
            { label: '仅 TLSv1.3', value: 'TLSv1.3' },
          ],
          default: 'TLSv1.2 TLSv1.3',
          dependsOn: { key: 'enableHttps', value: true },
        },
      ],
    },
    {
      title: '反向代理',
      fields: [
        {
          key: 'enableProxy',
          label: '开启反向代理',
          type: 'switch',
          default: false,
          tip: '将请求转发到后端应用服务器',
        },
        {
          key: 'proxyTarget',
          label: '后端地址',
          type: 'text',
          placeholder: 'http://127.0.0.1:8080',
          default: 'http://127.0.0.1:8080',
          dependsOn: { key: 'enableProxy', value: true },
          required: true,
        },
        {
          key: 'proxyPath',
          label: '代理路径前缀',
          type: 'text',
          placeholder: '/',
          default: '/',
          dependsOn: { key: 'enableProxy', value: true },
        },
      ],
    },
    {
      title: '高级选项',
      fields: [
        {
          key: 'enableCors',
          label: '开启跨域 (CORS)',
          type: 'switch',
          default: false,
          tip: '添加跨域资源共享响应头',
        },
        {
          key: 'clientMaxBodySize',
          label: '请求体最大限制',
          type: 'select',
          options: [
            { label: '1m', value: '1m' },
            { label: '10m', value: '10m' },
            { label: '50m', value: '50m' },
            { label: '100m', value: '100m' },
            { label: '1g', value: '1g' },
          ],
          default: '10m',
          tip: '文件上传大小限制',
        },
        {
          key: 'accessLog',
          label: '开启访问日志',
          type: 'switch',
          default: true,
        },
        {
          key: 'keepaliveTimeout',
          label: 'Keep-Alive 超时 (秒)',
          type: 'number',
          min: 5,
          max: 300,
          default: 65,
        },
      ],
    },
  ],
}

export function generateNginxConf(config) {
  const lines = []
  lines.push(`# NGINX 配置文件 - 由 ConfTemplate 生成`)
  lines.push(`# 生成时间: ${new Date().toLocaleString('zh-CN')}`)
  lines.push(``)
  lines.push(`user nginx;`)
  lines.push(`worker_processes ${config.workerProcesses};`)
  lines.push(`error_log /var/log/nginx/error.log warn;`)
  lines.push(`pid /var/run/nginx.pid;`)
  lines.push(``)
  lines.push(`events {`)
  lines.push(`    worker_connections ${config.workerConnections};`)
  lines.push(`}`)
  lines.push(``)
  lines.push(`http {`)
  lines.push(`    include       /etc/nginx/mime.types;`)
  lines.push(`    default_type  application/octet-stream;`)
  lines.push(``)

  if (config.accessLog) {
    lines.push(`    log_format main '$remote_addr - $remote_user [$time_local] "$request" '`)
    lines.push(`                    '$status $body_bytes_sent "$http_referer" '`)
    lines.push(`                    '"$http_user_agent" "$http_x_forwarded_for"';`)
    lines.push(``)
    lines.push(`    access_log /var/log/nginx/access.log main;`)
    lines.push(``)
  }

  lines.push(`    sendfile        on;`)
  lines.push(`    tcp_nopush      on;`)
  lines.push(`    tcp_nodelay     on;`)
  lines.push(`    keepalive_timeout ${config.keepaliveTimeout};`)
  lines.push(`    types_hash_max_size 2048;`)
  lines.push(`    client_max_body_size ${config.clientMaxBodySize};`)
  lines.push(``)

  if (config.enableGzip) {
    lines.push(`    # Gzip 压缩配置`)
    lines.push(`    gzip on;`)
    lines.push(`    gzip_vary on;`)
    lines.push(`    gzip_proxied any;`)
    lines.push(`    gzip_comp_level 6;`)
    lines.push(`    gzip_buffers 16 8k;`)
    lines.push(`    gzip_http_version 1.1;`)
    lines.push(`    gzip_min_length 256;`)
    lines.push(`    gzip_types ${config.gzipTypes};`)
    lines.push(``)
  }

  lines.push(`    # 上游服务器${config.enableProxy ? '' : ' (示例，未启用)'}`)
  lines.push(`    # upstream backend {`)
  lines.push(`    #     server 127.0.0.1:8080;`)
  lines.push(`    # }`)
  lines.push(``)

  lines.push(`    server {`)
  lines.push(`        listen ${config.httpPort};`)

  if (config.enableHttps) {
    lines.push(`        listen ${config.httpsPort} ssl http2;`)
  }

  lines.push(`        server_name ${config.serverName};`)
  lines.push(``)

  if (config.enableHttps) {
    lines.push(`        # SSL 证书配置`)
    lines.push(`        ssl_certificate     ${config.sslCertificate};`)
    lines.push(`        ssl_certificate_key ${config.sslCertificateKey};`)
    lines.push(`        ssl_protocols       ${config.sslProtocols};`)
    lines.push(`        ssl_ciphers         HIGH:!aNULL:!MD5;`)
    lines.push(`        ssl_prefer_server_ciphers on;`)
    lines.push(`        ssl_session_cache   shared:SSL:10m;`)
    lines.push(`        ssl_session_timeout 10m;`)
    lines.push(``)

    // HTTP to HTTPS redirect
    lines.push(`        # HTTP 自动跳转 HTTPS`)
    lines.push(`    }`)
    lines.push(``)
    lines.push(`    server {`)
    lines.push(`        listen 80;`)
    lines.push(`        server_name ${config.serverName};`)
    lines.push(`        return 301 https://$host$request_uri;`)
    lines.push(`    }`)
    lines.push(``)
    lines.push(`    server {`)
    lines.push(`        listen ${config.httpsPort} ssl http2;`)
    lines.push(`        server_name ${config.serverName};`)
    lines.push(`        ssl_certificate     ${config.sslCertificate};`)
    lines.push(`        ssl_certificate_key ${config.sslCertificateKey};`)
    lines.push(``)
  }

  if (config.enableCors) {
    lines.push(`        # 跨域配置 (CORS)`)
    lines.push(`        add_header 'Access-Control-Allow-Origin' '*' always;`)
    lines.push(`        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;`)
    lines.push(`        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;`)
    lines.push(`        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;`)
    lines.push(``)
    lines.push(`        if ($request_method = 'OPTIONS') {`)
    lines.push(`            add_header 'Access-Control-Allow-Origin' '*';`)
    lines.push(`            add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';`)
    lines.push(`            add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization';`)
    lines.push(`            add_header 'Access-Control-Max-Age' 1728000;`)
    lines.push(`            add_header 'Content-Type' 'text/plain; charset=utf-8';`)
    lines.push(`            add_header 'Content-Length' 0;`)
    lines.push(`            return 204;`)
    lines.push(`        }`)
    lines.push(``)
  }

  lines.push(`        location / {`)

  if (config.enableProxy) {
    lines.push(`            proxy_pass ${config.proxyTarget};`)
    lines.push(`            proxy_http_version 1.1;`)
    lines.push(`            proxy_set_header Upgrade $http_upgrade;`)
    lines.push(`            proxy_set_header Connection 'upgrade';`)
    lines.push(`            proxy_set_header Host $host;`)
    lines.push(`            proxy_set_header X-Real-IP $remote_addr;`)
    lines.push(`            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;`)
    lines.push(`            proxy_set_header X-Forwarded-Proto $scheme;`)
    lines.push(`            proxy_cache_bypass $http_upgrade;`)
  } else {
    lines.push(`            root /usr/share/nginx/html;`)
    lines.push(`            index index.html index.htm;`)
  }

  lines.push(`        }`)
  lines.push(``)
  lines.push(`        error_page 404 /404.html;`)
  lines.push(`        error_page 500 502 503 504 /50x.html;`)
  lines.push(`        location = /50x.html {`)
  lines.push(`            root /usr/share/nginx/html;`)
  lines.push(`        }`)
  lines.push(`    }`)
  lines.push(`}`)

  return lines.join('\n')
}
