import { defineStore, storeToRefs } from "pinia";
import { ref, computed } from "vue";
import { useProjectsStore } from "./projects";

export const useUserStore = defineStore("user", () => {
  const user = ref(null);

  const { projects } = storeToRefs(useProjectsStore());

  const notifications = computed(() => {
    return projects.value.flatMap((project) => {
      if (!project.notifications) return [];

      return project.notifications
        .filter((notification) => notification.author.uuid !== user.value.uuid)
        .map((notification) => ({
          ...notification,
          project: project,
          isRead: notification.readby?.includes(user.value.uuid),
        }));
    });
  });

  function readNotification(notificationId, projectId) {
    console.log("Read notification", notificationId, projectId);
    projects.value = projects.value.map((project) => ({
      ...project,
      notifications:
        project.uuid === projectId || project.uri === projectId
          ? project.notifications.map((notification) =>
              notification.id === notificationId
                ? {
                    ...notification,
                    readby: [
                      ...new Set([...notification.readby, user.value.uuid]),
                    ],
                  }
                : notification
            )
          : project.notifications,
    }));
  }

  function readAllNotifications() {
    projects.value = projects.value.map((project) => ({
      ...project,
      notifications: project.notifications.map((notification) => ({
        ...notification,
        readby: [...new Set([...notification.readby, user.value.uuid])],
      })),
    }));
  }

  function canEditComment(comment) {
    return user.value.uuid === comment.author.uuid;
  }

  return {
    user,
    notifications,
    readNotification,
    readAllNotifications,
    canEditComment,
  };
});
