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

// types
export type BlockedUsers = Exclude<ActionReturnType<typeof actions.user.blocked>['data'], undefined>['blocked'];
export type BlockedUser = BlockedUsers[0];

// state
export const blockedUsers = writable<BlockedUsers>([]);

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

  blockedUsers.set(data.blocked);
}

export async function addBlockedUser(blockedUser: BlockedUser) {
  const { data, error } = await actions.user.addBlocked(blockedUser);
  if (error) {
    actionErrorPopup(error);
    return;
  }

  addToWritableArray(blockedUsers, Object.assign(blockedUser, { id: data.id }));
}

export async function editBlockedUser(blockedUser: BlockedUser) {
  const { error } = await actions.user.editBlocked(blockedUser);
  if (error) {
    actionErrorPopup(error);
    return;
  }

  updateWritableArray(blockedUsers, blockedUser, (t) => t.id == blockedUser.id);
}

export async function deleteBlockedUser(blockedUser: BlockedUser) {
  const { error } = await actions.user.deleteBlocked(blockedUser);
  if (error) {
    actionErrorPopup(error);
    return;
  }

  deleteFromWritableArray(blockedUsers, (t) => t.id == blockedUser.id);
}
