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 StrikeReasons = Exclude<
  ActionReturnType<typeof actions.report.strikeReasons>['data'],
  undefined
>['strikeReasons'];
export type StrikeReason = StrikeReasons[0];

// state
export const strikeReasons = writable<StrikeReasons>([]);

// actions
export async function fetchStrikeReasons() {
  const { data, error } = await actions.report.strikeReasons();
  if (error) {
    actionErrorPopup(error);
    return;
  }

  strikeReasons.set(data.strikeReasons);
}

export async function addStrikeReason(strikeReason: StrikeReason) {
  const { data, error } = await actions.report.addStrikeReason(strikeReason);
  if (error) {
    actionErrorPopup(error);
    return;
  }

  addToWritableArray(strikeReasons, Object.assign(strikeReason, { id: data.id }));
}

export async function editStrikeReason(strikeReason: StrikeReason) {
  const { error } = await actions.report.editStrikeReason(strikeReason);
  if (error) {
    actionErrorPopup(error);
    return;
  }

  updateWritableArray(strikeReasons, strikeReason, (t) => t.id == strikeReason.id);
}

export async function deleteStrikeReason(strikeReason: StrikeReason) {
  const { error } = await actions.report.deleteStrikeReason(strikeReason);
  if (error) {
    actionErrorPopup(error);
    return;
  }

  deleteFromWritableArray(strikeReasons, (t) => t.id == strikeReason.id);
}
