<template>
  <NCard size="small">
    <NSpace
      align="center"
      justify="space-between"
    >
      <NSpace align="center">
        <NTag :type="ws.sync_status === 'idle' ? 'success' : ws.sync_status === 'error' ? 'error' : 'info'">
          {{ ws.sync_status }}
        </NTag>
        <span
          v-if="ws.last_synced_at"
          class="text-sm text-gray-500"
        >
          上次同步 {{ ws.last_synced_at }}
        </span>
        <span
          v-else
          class="text-sm text-gray-500"
        >尚未同步</span>
        <span
          v-if="ws.last_sync_error"
          class="text-sm text-red-600"
        >{{ ws.last_sync_error }}</span>
      </NSpace>
      <NButton
        :disabled="busy"
        type="primary"
        size="small"
        @click="onSync"
      >
        立即同步
      </NButton>
    </NSpace>
  </NCard>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { NCard, NTag, NButton, NSpace, useMessage } from 'naive-ui'
import { useWorkspacesStore } from '@/stores/workspaces'
import type { Workspace } from '@/api/types'

const props = defineProps<{ ws: Workspace }>()
const store = useWorkspacesStore()
const msg = useMessage()

const busy = computed(() => props.ws.sync_status === 'cloning' || props.ws.sync_status === 'syncing')

async function onSync() {
  // store.sync() 仅触发异步 fetch；要等真正落到 idle/error，必须 pollUntilSettled。
  try {
    await store.sync(props.ws.id)
    msg.info('已开始同步')
    await store.pollUntilSettled(props.ws.id)
    msg.success('已同步')
  } catch (e: unknown) {
    msg.error('同步失败：' + (e instanceof Error ? e.message : String(e)))
  }
}
</script>
