<script setup>
import BoardForm from '../components/Board/BoardForm.vue';
import BoardMessage from '../components/Board/BoardMessage.vue';
import { ref, onMounted } from 'vue';
import { postMessage, deleteMessage, getMessages } from '../lib/api';
import { useAuthStore } from '../stores/auth';

const messages = ref([]);

const authStore = useAuthStore();
const jwt = authStore.jwt;
const isLoggedIn = authStore.isLoggedIn;

onMounted(async () => {
  try {
    const response = await getMessages(jwt);
    messages.value = response.messages;
  } catch (error) {
    alert("Failed to get messages: " + error.message);
  }
});

const onSubmit = async (message) => {
  if (!isLoggedIn) return;

  try {
    await postMessage(message.text, jwt);

    const response = await getMessages();
    messages.value = response.messages;
  } catch (error) {
    alert("Failed to post message: " + error.message);
  }
};

const onDelete = async (messageId) => {
  try {
    await deleteMessage(messageId, jwt);

    const response = await getMessages();
    messages.value = response.messages;
  } catch (error) {
    alert("Failed to delete message: " + error.message);
  }
};
</script>

<template>
  <div class="ts-container">
    <BoardForm :locked="!isLoggedIn" @new-message="onSubmit" />
    <div class="ts-content is-horizontally-fitted is-vertically-padded">
      <div class="ts-wrap is-vertical">
        <BoardMessage :message="message" v-for="message in messages" :key="message.id" @delete-message="onDelete(message.id)" />
      </div>
    </div>
  </div>
</template>
