import {
  PrivateAlbum,
  PrivateAlbumSchema,
  type PrivateAlbumsResponse,
  type PrivateAlbumUnlockResponse,
} from "@/data/schemas/private-zone";

import type { PrivateZoneState } from "../private-zone-state";

export const PRIVATE_ZONE_PAGE_SIZE = 20;

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

export function getPendingAlbum(
  context: PrivateZoneState,
): 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 PrivateAlbumSchema.parse({
    ...album,
    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,
): readonly PrivateAlbum[] {
  return items.map((album) =>
    album.albumId === response.albumId
      ? patchAlbumFromUnlock(album, response)
      : album,
  );
}

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