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

import type { PrivateRoomState } from "../private-room-state";

export const PRIVATE_ROOM_CHARACTER = "elio";
export const PRIVATE_ROOM_PAGE_SIZE = 20;

export function applyAlbumsResponse(
  response: PrivateAlbumsResponse,
): Partial<PrivateRoomState> {
  return {
    items: response.items,
    creditBalance: response.creditBalance,
    errorMessage: null,
  };
}

export function getPendingAlbum(
  context: PrivateRoomState,
): PrivateAlbum | null {
  if (!context.pendingConfirmAlbumId) return null;
  return (
    context.items.find(
      (album) => album.albumId === context.pendingConfirmAlbumId,
    ) ?? null
  );
}

export function patchAlbumFromUnlock(
  album: PrivateAlbum,
  response: PrivateAlbumUnlockResponse,
): PrivateAlbum {
  return PrivateAlbum.from({
    ...album.toJson(),
    locked: response.locked,
    unlocked: response.unlocked,
    unlockCost: response.unlockCost || album.unlockCost,
    images: response.images.length > 0 ? response.images : album.images,
    lockDetail: { locked: response.locked },
  });
}

export function patchAlbumInList(
  items: readonly PrivateAlbum[],
  response: PrivateAlbumUnlockResponse,
): PrivateAlbum[] {
  return items.map((album) =>
    album.albumId === response.albumId
      ? patchAlbumFromUnlock(album, response)
      : album,
  );
}

export function removeAlbum(
  items: readonly PrivateAlbum[],
  albumId: string,
): PrivateAlbum[] {
  return items.filter((album) => album.albumId !== albumId);
}
