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

export const k8sRoleBindingSchema = {
  id: 'k8s-rolebinding',
  name: 'K8s RoleBinding',
  icon: 'Link',
  category: '云原生',
  description: 'Kubernetes 命名空间级角色绑定，将 Role 授予用户或服务账户',
  format: 'yaml',
  fileName: 'rolebinding.yaml',
  groups: [
    {
      title: '基础信息',
      fields: [
        {
          key: 'name',
          label: 'RoleBinding 名称',
          type: 'text',
          placeholder: 'my-rolebinding',
          default: 'my-rolebinding',
          required: true,
          tip: '将用作 RoleBinding 的 metadata.name',
        },
        {
          key: 'namespace',
          label: '命名空间',
          type: 'text',
          placeholder: 'default',
          default: 'default',
        },
      ],
    },
    {
      title: '角色引用',
      fields: [
        {
          key: 'roleName',
          label: 'Role 名称',
          type: 'text',
          placeholder: 'my-role',
          default: '',
          required: true,
          tip: '要绑定的 Role 名称',
        },
      ],
    },
    {
      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 generateK8sRoleBindingYaml(config) {
  const subject = {
    kind: config.subjectKind || 'ServiceAccount',
    name: config.subjectName,
  }
  if (config.subjectNamespace && config.subjectKind === 'ServiceAccount') {
    subject.namespace = config.subjectNamespace
  }
  if (config.subjectKind === 'User') {
    subject.apiGroup = 'rbac.authorization.k8s.io'
  }
  if (config.subjectKind === 'Group') {
    subject.apiGroup = 'rbac.authorization.k8s.io'
  }

  const roleBinding = {
    apiVersion: 'rbac.authorization.k8s.io/v1',
    kind: 'RoleBinding',
    metadata: {
      name: config.name,
      namespace: config.namespace,
    },
    roleRef: {
      apiGroup: 'rbac.authorization.k8s.io',
      kind: 'Role',
      name: config.roleName,
    },
    subjects: [subject],
  }

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

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