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

export const k8sClusterRoleBindingSchema = {
  id: 'k8s-clusterrolebinding',
  name: 'K8s ClusterRoleBinding',
  icon: 'Link2',
  category: '云原生',
  description: 'Kubernetes 集群级角色绑定，将 ClusterRole 授予用户或服务账户',
  format: 'yaml',
  fileName: 'clusterrolebinding.yaml',
  groups: [
    {
      title: '基础信息',
      fields: [
        {
          key: 'name',
          label: 'ClusterRoleBinding 名称',
          type: 'text',
          placeholder: 'my-clusterrolebinding',
          default: 'my-clusterrolebinding',
          required: true,
          tip: '将用作 ClusterRoleBinding 的 metadata.name',
        },
      ],
    },
    {
      title: '角色引用',
      fields: [
        {
          key: 'clusterRoleName',
          label: 'ClusterRole 名称',
          type: 'text',
          placeholder: 'my-cluster-role',
          default: '',
          required: true,
          tip: '要绑定的 ClusterRole 名称',
        },
      ],
    },
    {
      title: '主体配置',
      fields: [
        {
          key: 'subjectKind',
          label: '主体类型',
          type: 'select',
          options: [
            { label: 'User (用户)', value: 'User' },
            { label: 'Group (用户组)', value: 'Group' },
            { label: 'ServiceAccount (服务账户)', value: 'ServiceAccount' },
          ],
          default: 'ServiceAccount',
          tip: '要授权的主体类型',
        },
        {
          key: 'subjectName',
          label: '主体名称',
          type: 'text',
          placeholder: 'my-serviceaccount',
          default: '',
          required: true,
          tip: '用户、组或 ServiceAccount 的名称',
        },
        {
          key: 'subjectNamespace',
          label: '主体命名空间',
          type: 'text',
          placeholder: '仅 ServiceAccount 需要',
          default: '',
          tip: '仅当主体类型为 ServiceAccount 时需要填写',
        },
      ],
    },
  ],
}

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 generateK8sClusterRoleBindingYaml(config) {
  const subject = {
    kind: config.subjectKind || 'ServiceAccount',
    name: config.subjectName,
  }
  if (config.subjectNamespace && config.subjectKind === 'ServiceAccount') {
    subject.namespace = config.subjectNamespace
  }
  if (config.subjectKind === 'User' || config.subjectKind === 'Group') {
    subject.apiGroup = 'rbac.authorization.k8s.io'
  }

  const clusterRoleBinding = {
    apiVersion: 'rbac.authorization.k8s.io/v1',
    kind: 'ClusterRoleBinding',
    metadata: {
      name: config.name,
    },
    roleRef: {
      apiGroup: 'rbac.authorization.k8s.io',
      kind: 'ClusterRole',
      name: config.clusterRoleName,
    },
    subjects: [subject],
  }

  const header = `# K8s ClusterRoleBinding - 由 ConfTemplate 生成
# 生成时间: ${new Date().toLocaleString('zh-CN')}
# 部署命令: kubectl apply -f ${config.fileName || 'clusterrolebinding.yaml'}
`

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