import { fromPromise } from "xstate";

import type {
  PrivateRoomMomentsResponse,
  PrivateRoomUnlockResponse,
} from "@/data/dto/private-room";
import { getPrivateRoomRepository } from "@/data/repositories/private_room_repository";
import { Result } from "@/utils";

import {
  PRIVATE_ROOM_CHARACTER,
  PRIVATE_ROOM_PAGE_SIZE,
} from "./private-room-machine.helpers";

export const loadPrivateRoomMomentsActor =
  fromPromise<PrivateRoomMomentsResponse>(async () => {
    const repo = getPrivateRoomRepository();
    const result = await repo.getMoments({
      character: PRIVATE_ROOM_CHARACTER,
      limit: PRIVATE_ROOM_PAGE_SIZE,
    });
    if (Result.isErr(result)) throw result.error;
    return result.data;
  });

export const loadMorePrivateRoomMomentsActor = fromPromise<
  PrivateRoomMomentsResponse,
  { cursor: string | null }
>(async ({ input }) => {
  const repo = getPrivateRoomRepository();
  const result = await repo.getMoments({
    character: PRIVATE_ROOM_CHARACTER,
    limit: PRIVATE_ROOM_PAGE_SIZE,
    cursor: input.cursor,
  });
  if (Result.isErr(result)) throw result.error;
  return result.data;
});

export const unlockPrivateRoomMomentActor = fromPromise<
  PrivateRoomUnlockResponse,
  { momentId: string; expectedCost: number }
>(async ({ input }) => {
  const repo = getPrivateRoomRepository();
  const result = await repo.unlockMoment(
    input.momentId,
    input.expectedCost,
  );
  if (Result.isErr(result)) throw result.error;
  return result.data;
});
