<template>
  <button class="btn btn-secondary" :disabled="sending" @click="emailReport">
    {{ sending ? 'Sending...' : 'Email report' }}
  </button>
</template>

<script setup>
import { ref } from 'vue'
import { reportsApi } from '../api'
import { useToast } from '../composables/toast'
import { apiError } from '../utils/apiError'

// On-demand report delivery. Emails the given rows as an HTML table to the
// site's Alert Recipients (or an explicit `to`). Automatic/scheduled sending is
// out of scope for this app; point an external cron at POST /api/reports/email
// with an API token to automate.
const props = defineProps({
  subject: { type: String, required: true },
  columns: { type: Array, required: true },
  rows: { type: Array, required: true },
  intro: { type: String, default: '' },
  to: { type: String, default: '' },
})

const toast = useToast()
const sending = ref(false)

async function emailReport() {
  sending.value = true
  try {
    const payload = {
      subject: props.subject,
      columns: props.columns,
      rows: props.rows,
      intro: props.intro,
    }
    if (props.to) payload.to = props.to
    const response = await reportsApi.email(payload)
    const result = response.data?.data || {}
    if (result.sent) {
      toast.success('Report emailed.')
    } else if (result.error) {
      toast.error(`Report email failed: ${result.error}`)
    } else {
      toast.info(response.data?.message || 'Email is not configured.')
    }
  } catch (event) {
    toast.error(apiError(event, 'Failed to email report'))
  } finally {
    sending.value = false
  }
}
</script>
