<script setup>
import { ref } from 'vue'

import ContactTable from './components/ContactTable.vue'
import ContactsSummary from './components/ContactsSummary.vue';
import Error from './components/Error.vue';

const referenceId = ref('')
const contactData = ref(null)
const errorMessage = ref(null)

function onInput(e) {
  referenceId.value = e.target.value
}

function fetchData() {
  //clear errors
  errorMessage.value = null
  contactData.value = null
  fetch(`${import.meta.env.VITE_EO_SERVICES_URL}/unified-data-gateway?referenceId=${ referenceId.value }`, {
      credentials: "include" // fetch won't send cookies unless you set credentials
    }).then (async response => {
      const data = await response.json();

      // check for error response
      if (!response.ok) {
        // get error message from body or default to response statusText
        const error = data  || response.statusText;
        return Promise.reject(error);
      }
    contactData.value = await data;
    }).catch(error => {
      errorMessage.value = error;
    });
}

</script>
<template>
  <div id="app">
    <div>
      <label for="referenceId">Reference ID: </label>
      <input id="referenceId" :value="referenceId" @input="onInput" placeholder="enter Reference ID here" />
      <button @click="fetchData">Search Contacts</button>
    </div>

    <ContactsSummary v-if="contactData" :summary="contactData.data.summary" />
    <div v-else>No Contacts Found</div>
    <ContactTable v-if="contactData" :tableData="contactData.data.findContactsCompletedBetween.edges" />
    <Error v-if="errorMessage" :errorMessage="errorMessage" />

  </div>
</template>
<style scoped>

</style>

