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

import type { PrivateAlbumsResponse } from "@/data/schemas/private-zone";

import { applyAlbumsResponse } from "../helper/albums";
import { toPrivateZoneErrorMessage } from "../helper/unlock";
import {
  basePrivateZoneMachineSetup,
  createPrivateZoneActorActionSetup,
} from "./setup";

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

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

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

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

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

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

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

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