<script setup lang="ts">
import { request, unwrapApiBody, type ApiResponse } from '../../../../utils/http/factory'
import { useAuthSession } from '../../../../composables/useAuthSession'

definePageMeta({ title: '应用配置' })

type GlobalConfigPayload = {
  config: {
    siteName: string
    allowRegister: boolean
  }
}

const { user, refresh } = useAuthSession()
const { refresh: refreshGlobalConfig } = useGlobalConfig()

const loading = ref(true)
const saving = ref(false)
const siteName = ref('')
const allowRegister = ref(true)

async function ensureAdmin() {
  await refresh(true)
  if (user.value?.role !== 'admin') {
    await navigateTo('/me')
  }
}

async function load() {
  loading.value = true
  try {
    const res = await request<ApiResponse<GlobalConfigPayload>>('/api/config/global')
    const cfg = unwrapApiBody(res).config
    siteName.value = cfg.siteName
    allowRegister.value = cfg.allowRegister
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  await ensureAdmin()
  await load()
})

async function putKey(key: string, value: unknown) {
  await request('/api/config/global', {
    method: 'PUT',
    body: { key, value },
  })
}

async function save() {
  saving.value = true
  try {
    await putKey('siteName', siteName.value.trim())
    await putKey('allowRegister', allowRegister.value)
    await load()
    await refreshGlobalConfig()
  } finally {
    saving.value = false
  }
}
</script>

<template>
  <UContainer class="py-8 space-y-8 max-w-4xl">
    <h1 class="text-2xl font-semibold">
      应用配置
    </h1>
    <p class="text-sm text-muted">
      全局设置：站点名称与开放注册。
    </p>

    <UCard>
      <template #header>
        全局项
      </template>
      <div v-if="loading" class="text-muted">
        加载中…
      </div>
      <div v-else class="space-y-4 max-w-xl">
        <UFormField label="站点名称">
          <UInput v-model="siteName" maxlength="64" placeholder="Person Panel" />
        </UFormField>
        <UFormField
          label="允许自助注册"
          description="关闭后，登录页不再显示注册入口；管理员仍可创建用户。"
        >
          <UCheckbox v-model="allowRegister" label="开启" />
        </UFormField>
        <UButton :loading="saving" @click="save">
          保存
        </UButton>
      </div>
    </UCard>
  </UContainer>
</template>
