﻿<template>
  <v-infinite-scroll
      :items="messages"
      :onLoad="fetchMessages"
      mode="manual"
      class="justify-items-center"
  >
    <template v-for="message in messages" :key="message">
      <message :message="message"
               class="border-b"
      ></message>
    </template>

    <template v-slot:load-more="{ props }">
      <v-btn size="small" variant="outlined" v-bind="props">
        Voir plus de commentaires
      </v-btn>
    </template>

    <template v-slot:empty>
      Il n'y a pas plus de commentaires
    </template>

    <template v-slot:error>
      <v-alert type="error">{{ errorMessage }}</v-alert>
    </template>
  </v-infinite-scroll>
</template>

<script setup>
import {ref, onBeforeMount} from 'vue';
import {useClient} from '@/plugins/api.js';
import Message from "@/views/messages/Message.vue";

const props = defineProps({
  subjectId: {
    type: String,
    required: true,
  },
  messages: {
    type: Array,
    default: () => [],
  },
});

const errorMessage = ref(null);
let last_id = null;
const client = useClient();
const messages = ref(props.messages);

onBeforeMount(async () => {
  if (props.subjectId == null) return;
  await fetchMessages({
    page_size: 2,
    done: function (status) {
    },
  });
});

async function fetchMessages({done, page_size = 10}) {
  if (props.subjectId == null) return

  try {
    let uri = `/api/messages/${props.subjectId}?page_size=${page_size}`;
    if (last_id !== null) uri = uri + `&last_id=${last_id}`;

    const response = await client.get(uri);

    if (response.status >= 200 && response.status < 300) {
      const messageCount = response.data.messages.length;

      if (messageCount > 0) {
        messages.value.push(...response.data.messages);
        const [last_content] = response.data.messages.slice(-1);
        last_id = last_content.id;
      }

      if (messageCount < page_size) {
        done('empty');
      } else {
        done('ok');
      }
    }
  } catch (error) {
    console.error("Failed to fetch messages", error);
    errorMessage.value = error.message || "Failed to fetch messages";
    done('error');
  }
}
</script>
