import { fromPromise } from "xstate";

import type {
  PrivateZonePostsResponse,
  PrivateZonePostUnlockResponse,
} from "@/data/schemas/private-zone";
import { getPrivateZonePostRepository } from "@/data/repositories/private_zone_post_repository";
import { Result } from "@/utils/result";

export const PRIVATE_ZONE_POST_PAGE_SIZE = 20;

export const loadPrivateZonePostsActor = fromPromise<
  PrivateZonePostsResponse,
  { characterId: string; cursor?: string | null }
>(async ({ input }) => {
  const result = await getPrivateZonePostRepository().getPosts({
    characterId: input.characterId,
    cursor: input.cursor,
    limit: PRIVATE_ZONE_POST_PAGE_SIZE,
  });
  if (Result.isErr(result)) throw result.error;
  return result.data;
});

export const unlockPrivateZonePostActor = fromPromise<
  PrivateZonePostUnlockResponse,
  { postId: string; expectedCost: number }
>(async ({ input }) => {
  const result = await getPrivateZonePostRepository().unlockPost(
    input.postId,
    input.expectedCost,
  );
  if (Result.isErr(result)) throw result.error;
  return result.data.postId
    ? result.data
    : { ...result.data, postId: input.postId };
});
