import type {
  PrivateRoomMoment,
  PrivateRoomMomentsResponse,
  PrivateRoomUnlockResponse,
} from "@/data/dto/private-room";

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

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

export function applyMomentsResponse(
  response: PrivateRoomMomentsResponse,
): Partial<PrivateRoomState> {
  return {
    profile: response.profile,
    items: response.items,
    nextCursor: response.nextCursor,
    hasMore: response.hasMore,
    creditBalance: response.creditBalance,
    errorMessage: null,
  };
}

export function appendMomentsResponse(
  context: PrivateRoomState,
  response: PrivateRoomMomentsResponse,
): Partial<PrivateRoomState> {
  const knownIds = new Set(context.items.map((item) => item.momentId));
  const nextItems = [
    ...context.items,
    ...response.items.filter((item) => !knownIds.has(item.momentId)),
  ];
  return {
    profile: response.profile,
    items: nextItems,
    nextCursor: response.nextCursor,
    hasMore: response.hasMore,
    creditBalance: response.creditBalance,
    errorMessage: null,
  };
}

export function replaceMoment(
  items: readonly PrivateRoomMoment[],
  nextMoment: PrivateRoomMoment,
): PrivateRoomMoment[] {
  return items.map((item) =>
    item.momentId === nextMoment.momentId ? nextMoment : item,
  );
}

export function toPrivateRoomErrorMessage(error: unknown): string {
  if (error instanceof Error && error.message) return error.message;
  return "Private room is temporarily unavailable. Please try again.";
}

export function toUnlockErrorMessage(
  response: PrivateRoomUnlockResponse,
): string | null {
  switch (response.reason) {
    case "cost_changed":
      return "Unlock price changed. Please confirm again.";
    case "not_found":
      return "This private room post is no longer available.";
    case "no_media":
      return "This private room post has no photos to unlock.";
    case "deduct_failed":
      return "Credit deduction failed. Please try again.";
    default:
      return response.unlocked ? null : "Unlock failed. Please try again.";
  }
}

export function toPaywallRequest(
  response: PrivateRoomUnlockResponse,
): PrivateRoomUnlockPaywallRequest {
  return {
    momentId: response.momentId,
    reason: response.reason,
    requiredCredits: response.requiredCredits,
    currentCredits: response.currentCredits || response.creditBalance,
    shortfallCredits: response.shortfallCredits,
  };
}
