import { type ActionReturnType, actions } from 'astro:actions';
import { writable } from 'svelte/store';
import { actionErrorPopup } from '@util/action.ts';
import { addToWritableArray, deleteFromWritableArray } from '@util/state.ts';

// types
export type DirectInvitations = Exclude<
  ActionReturnType<typeof actions.user.directInvitations>['data'],
  undefined
>['directInvitations'];
export type DirectInvitation = DirectInvitations[0];

// state
export const directInvitations = writable<DirectInvitations>([]);

// actions
export async function fetchDirectInvitations() {
  const { data, error } = await actions.user.directInvitations();
  if (error) {
    actionErrorPopup(error);
    return;
  }

  directInvitations.set(data.directInvitations);
}

export async function addDirectInvitation() {
  const { data, error } = await actions.user.addDirectInvitation();
  if (error) {
    actionErrorPopup(error);
    return;
  }

  addToWritableArray(directInvitations, data);
}

export async function deleteDirectInvitation(directInvitation: DirectInvitation) {
  const { error } = await actions.user.deleteDirectInvitation(directInvitation);
  if (error) {
    actionErrorPopup(error);
    return;
  }

  deleteFromWritableArray(directInvitations, (i) => i.hash === directInvitation.hash);
}
