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 Admins = Exclude<ActionReturnType<typeof actions.admin.admins>['data'], undefined>['admins'];
export type Admin = Admins[0];

// state
export const admins = writable<Admin[]>([]);

// actions
export async function fetchAdmins() {
  const { data, error } = await actions.admin.admins();
  if (error) {
    actionErrorPopup(error);
    return;
  }

  admins.set(data.admins);
}

export async function addAdmin(admin: Admin & { password: string }) {
  const { data, error } = await actions.admin.addAdmin(admin);
  if (error) {
    actionErrorPopup(error);
    return;
  }

  addToWritableArray(admins, Object.assign(admin, { id: data.id }));
}

export async function editAdmin(admin: Admin & { password: string }) {
  const { error } = await actions.admin.editAdmin(admin);
  if (error) {
    actionErrorPopup(error);
    return;
  }

  updateWritableArray(admins, admin, (t) => t.id == admin.id);
}

export async function deleteAdmin(admin: Admin) {
  const { error } = await actions.admin.deleteAdmin(admin);
  if (error) {
    actionErrorPopup(error);
    return;
  }

  deleteFromWritableArray(admins, (t) => t.id == admin.id);
}
