<script setup lang="ts">
import { NInput } from 'naive-ui'
import { computed, ref, watch } from 'vue'

import { createConsoleConnection } from '@/api/instances'
import FormField from '@/components/FormField.vue'
import FormModal from '@/components/FormModal.vue'
import { useToast } from '@/composables/useToast'

const props = defineProps<{ show: boolean; cfgId: number; instanceId: string; region?: string }>()
const emit = defineEmits<{ 'update:show': [boolean]; created: [] }>()

const message = useToast()
const submitting = ref(false)
const publicKey = ref('')

watch(
  () => props.show,
  (v) => {
    if (v) publicKey.value = ''
  },
)

const isRsa = computed(() => publicKey.value.trim().startsWith('ssh-rsa '))

async function submit() {
  submitting.value = true
  try {
    await createConsoleConnection(props.cfgId, props.instanceId, publicKey.value.trim(), props.region)
    message.success('控制台连接已创建，稍候列表刷新出连接串')
    emit('update:show', false)
    emit('created')
  } catch (e) {
    message.error(e instanceof Error ? e.message : '创建失败')
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <FormModal
    :show="show"
    title="创建控制台连接"
    :width="560"
    :submitting="submitting"
    :submit-disabled="!isRsa"
    submit-text="创建"
    @update:show="emit('update:show', $event)"
    @submit="submit"
  >
    <FormField
      label="SSH 公钥（仅 RSA）"
      required
      hint="生成示例：ssh-keygen -t rsa -b 4096 -f console_key"
      :error="
        publicKey.trim() && !isRsa
          ? '必须以 ssh-rsa 开头 —— OCI 控制台连接不接受 ed25519 等其他算法'
          : undefined
      "
    >
      <NInput
        v-model:value="publicKey"
        type="textarea"
        :rows="4"
        class="mono"
        placeholder="ssh-rsa AAAAB3…"
      />
    </FormField>
    <div class="text-xs leading-relaxed text-ink-3">
      创建后用对应私钥执行连接串：串口直接执行 connectionString；VNC 执行 vncConnectionString
      建立隧道后，用 VNC 客户端连 localhost:5900。
    </div>
  </FormModal>
</template>
