<template>
  <div>
    <el-form :model="form" label-width="140px" style="max-width: 600px;">
      <el-form-item label="入站 Webhook URL">
        <el-input v-model="form.inbound_webhook_url" placeholder="https://example.com/webhook" />
      </el-form-item>
      <el-form-item label="签名算法">
        <el-select v-model="form.sign_algorithm" placeholder="选择签名算法">
          <el-option label="HMAC-SHA256" value="hmac-sha256" />
          <el-option label="HMAC-SHA512" value="hmac-sha512" />
        </el-select>
      </el-form-item>
      <el-form-item label="Webhook Secret">
        <el-input v-model="form.webhook_secret" type="password" show-password placeholder="用于签名验证的密钥" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSave">保存</el-button>
        <el-button @click="handleTest">测试推送</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getInboundWebhookConfig, updateInboundWebhookConfig, testInboundWebhook } from '@/api/inboundWebhook'

const form = reactive({
  inbound_webhook_url: '',
  sign_algorithm: 'hmac-sha256',
  webhook_secret: '',
})

async function loadConfig() {
  try {
    const res: any = await getInboundWebhookConfig()
    const data = res.data || {}
    form.inbound_webhook_url = data.inbound_webhook_url || ''
    const authConfig = data.auth_config || {}
    form.sign_algorithm = authConfig.sign_algorithm || 'hmac-sha256'
    form.webhook_secret = authConfig.webhook_secret || ''
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

async function handleSave() {
  try {
    await updateInboundWebhookConfig({
      inbound_webhook_url: form.inbound_webhook_url,
      auth_config: {
        sign_algorithm: form.sign_algorithm,
        webhook_secret: form.webhook_secret,
      },
    })
    ElMessage.success('保存成功')
    await loadConfig()
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

async function handleTest() {
  if (!form.inbound_webhook_url) {
    ElMessage.warning('请先填写 Webhook URL')
    return
  }
  try {
    const res: any = await testInboundWebhook({ url: form.inbound_webhook_url })
    const result = res.data || {}
    ElMessageBox.alert(result.message || '测试完成', result.success ? '测试成功' : '测试失败', {
      type: result.success ? 'success' : 'error',
    })
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

onMounted(() => {
  loadConfig()
})
</script>
