<template>
  <div class="space-y-6 p-4">
    <!-- Fetch Message History -->
    <div class="space-y-4">
      <h3 class="text-lg font-medium text-[var(--wa-text)]">Solicitar Historial de Mensajes</h3>
      <p class="text-sm text-[var(--wa-text-muted)]">
        Solicita mensajes adicionales del historial. Los resultados llegaran via el evento messaging-history.set.
      </p>
      <div class="grid grid-cols-2 gap-4">
        <UInput
          v-model.number="count"
          type="number"
          placeholder="Cantidad de mensajes"
          :min="1"
          :max="1000"
        />
        <UInput
          v-model.number="oldestMsgTimestamp"
          type="number"
          placeholder="Timestamp mas antiguo (opcional)"
        />
      </div>
      <div class="space-y-2">
        <p class="text-sm text-[var(--wa-text-muted)]">Oldest Message Key (opcional, JSON):</p>
        <UTextarea
          v-model="oldestMsgKeyJson"
          placeholder='{"remoteJid": "...", "id": "...", "fromMe": false}'
          :rows="3"
          class="font-mono text-sm"
        />
      </div>
      <UButton
        :loading="loading"
        :disabled="!instanceId || !count"
        @click="fetchHistory"
      >
        Solicitar Historial
      </UButton>
    </div>
  </div>
</template>

<script setup lang="ts">
const props = defineProps<{
  instanceId: string | null
}>()

const emit = defineEmits<{
  (e: 'response', data: any): void
}>()

const count = ref<number>(50)
const oldestMsgTimestamp = ref<number | null>(null)
const oldestMsgKeyJson = ref('')
const loading = ref(false)

const fetchHistory = async () => {
  loading.value = true
  try {
    let oldestMsgKey = undefined
    if (oldestMsgKeyJson.value.trim()) {
      try {
        oldestMsgKey = JSON.parse(oldestMsgKeyJson.value)
      } catch {
        emit('response', { success: false, error: 'Invalid JSON for oldestMsgKey' })
        loading.value = false
        return
      }
    }

    const result = await $fetch('/api/debug/history/fetch', {
      method: 'POST',
      body: {
        instanceId: props.instanceId,
        count: count.value,
        oldestMsgKey,
        oldestMsgTimestamp: oldestMsgTimestamp.value || undefined
      }
    })
    emit('response', result)
  } catch (error: any) {
    emit('response', { success: false, error: error.data?.message || error.message })
  } finally {
    loading.value = false
  }
}
</script>
