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

// types
export type Users = Exclude<ActionReturnType<typeof actions.user.users>['data'], undefined>['users'];
export type User = Users[0];

// state
export const users = writable<Users>([]);

// actions
export async function fetchUsers(options?: { username?: string | null }) {
  const { data, error } = await actions.user.users({ username: options?.username });
  if (error) {
    actionErrorPopup(error);
    return;
  }

  users.set(data.users);
}

export async function addUser(user: User) {
  const { data, error } = await actions.user.addUser({
    firstname: user.firstname,
    lastname: user.lastname,
    birthday: user.birthday,
    telephone: user.telephone,
    username: user.username,
    edition: user.edition,
    uuid: user.uuid
  });
  if (error) {
    actionErrorPopup(error);
    return;
  }

  addToWritableArray(users, Object.assign(user, { id: data.id }));
}

export async function editUser(user: User) {
  const { error } = await actions.user.editUser({
    id: user.id,
    firstname: user.firstname,
    lastname: user.lastname,
    birthday: user.birthday,
    telephone: user.telephone,
    username: user.username,
    edition: user.edition,
    uuid: user.uuid
  });
  if (error) {
    actionErrorPopup(error);
    return;
  }

  updateWritableArray(users, user, (t) => t.id == user.id);
}

export async function blockUser(user: User) {
  if (!user.uuid) return;

  const { error } = await actions.user.addBlocked({ uuid: user.uuid, comment: null });
  if (error) {
    actionErrorPopup(error);
    return;
  }
}

export async function deleteUser(user: User) {
  const { error } = await actions.user.deleteUser({ id: user.id });
  if (error) {
    actionErrorPopup(error);
    return;
  }

  deleteFromWritableArray(users, (t) => t.id == user.id);
}
