<script setup lang="ts">
import { useAuthSession } from '../../../../composables/useAuthSession'

usePageTitle('应用配置')

type GlobalConfigPayload = {
  config: {
    siteName: string
    allowRegister: boolean
    mediaOrphanAutoSweepEnabled: boolean
    mediaOrphanAutoSweepIntervalMinutes: number
  }
}

const { user, refresh } = useAuthSession()
const { fetchData } = useClientApi()
const toast = useToast()
const { refresh: refreshGlobalConfig } = useGlobalConfig()

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

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

async function load() {
  loading.value = true
  try {
    const { config: cfg } = await fetchData<GlobalConfigPayload>('/api/config/global')
    siteName.value = cfg.siteName
    allowRegister.value = cfg.allowRegister
    mediaOrphanAutoSweepEnabled.value = cfg.mediaOrphanAutoSweepEnabled
    mediaOrphanAutoSweepIntervalMinutes.value = cfg.mediaOrphanAutoSweepIntervalMinutes
  } finally {
    loading.value = false
  }
}

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

async function putKey(key: string, value: unknown) {
  await fetchData('/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 putKey('mediaOrphanAutoSweepEnabled', mediaOrphanAutoSweepEnabled.value)
    await putKey('mediaOrphanAutoSweepIntervalMinutes', mediaOrphanAutoSweepIntervalMinutes.value)
    await load()
    await refreshGlobalConfig()
    toast.add({ title: '配置已保存', color: 'success' })
  } 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>
        <UFormField
          label="媒体孤儿自动清扫"
          description="全站生效、仅删除已过宽限期且无引用的图片、建议先在「图片孤儿审查」确认。"
        >
          <UCheckbox v-model="mediaOrphanAutoSweepEnabled" label="开启定时自动清扫" />
        </UFormField>
        <UFormField
          label="清扫间隔（分钟）"
          description="15–1440；与定时任务触发频率配合，任务内会按此间隔节流。"
        >
          <UInput
            v-model.number="mediaOrphanAutoSweepIntervalMinutes"
            type="number"
            :min="15"
            :max="1440"
            step="1"
          />
        </UFormField>
        <UButton :loading="saving" @click="save">
          保存
        </UButton>
      </div>
    </UCard>
  </UContainer>
</template>
