import type { DoneActorEvent, ErrorActorEvent } from "xstate";

import type { PrivateAlbumsResponse } from "@/data/dto/private-room";

import { applyAlbumsResponse } from "../helper/albums";
import { toPrivateRoomErrorMessage } from "../helper/unlock";
import {
  basePrivateRoomMachineSetup,
  createPrivateRoomActorActionSetup,
} from "./setup";

const clearAlbumLoadStateAction = basePrivateRoomMachineSetup.assign({
  errorMessage: null,
  unlockPaywallRequest: null,
});

export const albumMachineSetup = basePrivateRoomMachineSetup.extend({
  actions: {
    clearAlbumLoadState: clearAlbumLoadStateAction,
  },
});

const albumsDoneSetup =
  createPrivateRoomActorActionSetup<
    DoneActorEvent<PrivateAlbumsResponse>
  >();
const albumErrorSetup =
  createPrivateRoomActorActionSetup<ErrorActorEvent>();

const applyAlbumsResponseAction = albumsDoneSetup.assign(({ event }) =>
  applyAlbumsResponse(event.output),
);

const applyAlbumLoadErrorAction = albumErrorSetup.assign(({ event }) => ({
  errorMessage: toPrivateRoomErrorMessage(event.error),
}));

export const idleState = albumMachineSetup.createStateConfig({
  on: {
    PrivateRoomInit: "loading",
  },
});

export const loadingState = albumMachineSetup.createStateConfig({
  entry: "clearAlbumLoadState",
  invoke: {
    src: "loadAlbums",
    onDone: {
      target: "ready",
      actions: applyAlbumsResponseAction,
    },
    onError: {
      target: "failed",
      actions: applyAlbumLoadErrorAction,
    },
  },
});

export const failedState = albumMachineSetup.createStateConfig({
  on: {
    PrivateRoomInit: "loading",
    PrivateRoomRefresh: "loading",
  },
});
