import { setup, type ActionFunction, type EventObject } from "xstate";

import type { UserEvent } from "../user-events";
import type { UserState } from "../user-state";
import { userFetchActor } from "./actors/profile";
import { userInitActor, userLogoutActor } from "./actors/session";

export const baseUserMachineSetup = setup({
  types: {
    context: {} as UserState,
    events: {} as UserEvent,
  },
  actors: {
    userInit: userInitActor,
    userFetch: userFetchActor,
    userLogout: userLogoutActor,
  },
});

type UserActorAction<TEvent extends EventObject> = ActionFunction<
  UserState,
  TEvent,
  UserEvent,
  undefined,
  never,
  never,
  never,
  never,
  never
>;

export function createUserActorActionSetup<TEvent extends EventObject>() {
  const actorActionSetup = setup({
    types: {
      context: {} as UserState,
      events: {} as TEvent,
    },
  });
  return {
    assign(
      assignment: Parameters<typeof actorActionSetup.assign>[0],
    ): UserActorAction<TEvent> {
      return actorActionSetup.assign(assignment) as unknown as UserActorAction<TEvent>;
    },
  };
}
