// K8s Secret Schema - 由 ConfTemplate 生成
// 生成时间: 自动生成

export const k8sSecretSchema = {
  id: 'k8s-secret',
  name: 'K8s Secret',
  icon: 'Lock',
  category: '云原生',
  description: 'Kubernetes Secret，存储敏感数据如密码、证书等',
  format: 'yaml',
  fileName: 'secret.yaml',
  groups: [
    {
      title: '基础信息',
      fields: [
        {
          key: 'name',
          label: 'Secret 名称',
          type: 'text',
          placeholder: 'my-secret',
          default: 'my-secret',
          required: true,
          tip: '将用作 Secret 的 metadata.name',
        },
        {
          key: 'namespace',
          label: '命名空间',
          type: 'text',
          placeholder: 'default',
          default: 'default',
        },
        {
          key: 'secretType',
          label: 'Secret 类型',
          type: 'select',
          options: [
            { label: 'Opaque (通用)', value: 'Opaque' },
            { label: 'Docker Registry (dockerconfigjson)', value: 'kubernetes.io/dockerconfigjson' },
            { label: 'TLS 证书', value: 'kubernetes.io/tls' },
            { label: 'Basic Auth (基础认证)', value: 'kubernetes.io/basic-auth' },
          ],
          default: 'Opaque',
          tip: '不同类型对应不同的数据结构',
        },
      ],
    },
    {
      title: '数据配置',
      fields: [
        {
          key: 'dataKey',
          label: '数据键名',
          type: 'text',
          placeholder: 'username',
          default: 'username',
          required: true,
          tip: 'Secret 中的键名',
        },
        {
          key: 'dataValue',
          label: '数据值',
          type: 'text',
          placeholder: 'base64 encoded or plain text',
          default: '',
          required: true,
          tip: '如果开启 Base64 编码，输入明文即可',
        },
        {
          key: 'encodeBase64',
          label: 'Base64 编码',
          type: 'switch',
          default: true,
          tip: '自动将数据值进行 Base64 编码',
        },
      ],
    },
    {
      title: '挂载配置',
      fields: [
        {
          key: 'mountAsVolume',
          label: '作为 Volume 挂载',
          type: 'switch',
          default: true,
          tip: '是否将 Secret 挂载为容器内的文件',
        },
        {
          key: 'mountPath',
          label: '挂载路径',
          type: 'text',
          placeholder: '/etc/secrets',
          default: '/etc/secrets',
          dependsOn: { key: 'mountAsVolume', value: true },
          tip: '容器内挂载目录路径',
        },
      ],
    },
  ],
}

function toYaml(obj, indent = 0) {
  const lines = []
  const prefix = '  '.repeat(indent)

  for (const [key, value] of Object.entries(obj)) {
    if (value === null || value === undefined || value === '') continue

    if (Array.isArray(value)) {
      lines.push(`${prefix}${key}:`)
      for (const item of value) {
        if (typeof item === 'object' && item !== null) {
          const entries = Object.entries(item).filter(([, v]) => v !== null && v !== undefined && v !== '')
          if (entries.length === 0) continue
          const first = entries[0]
          lines.push(`${prefix}  - ${first[0]}: ${first[1]}`)
          for (let i = 1; i < entries.length; i++) {
            lines.push(`${prefix}    ${entries[i][0]}: ${entries[i][1]}`)
          }
        } else {
          lines.push(`${prefix}  - ${item}`)
        }
      }
    } else if (typeof value === 'object') {
      lines.push(`${prefix}${key}:`)
      lines.push(toYaml(value, indent + 1))
    } else {
      lines.push(`${prefix}${key}: ${value}`)
    }
  }

  return lines.join('\n')
}

export function generateK8sSecretYaml(config) {
  const data = {}
  let value = config.dataValue || ''

  if (config.encodeBase64) {
    try {
      value = btoa(unescape(encodeURIComponent(value)))
    } catch {
      // fallback: use value as-is
    }
  }

  data[config.dataKey || 'data'] = value

  const secret = {
    apiVersion: 'v1',
    kind: 'Secret',
    metadata: {
      name: config.name,
      namespace: config.namespace,
    },
    type: config.secretType || 'Opaque',
    data,
  }

  const header = `# K8s Secret - 由 ConfTemplate 生成
# 生成时间: ${new Date().toLocaleString('zh-CN')}
# 部署命令: kubectl apply -f ${config.fileName || 'secret.yaml'}
# 注意: 生产环境建议使用 kubectl create secret 命令或 Sealed Secrets
`

  return header + '\n' + toYaml(secret)
}
