import type { UiMessage } from "@/data/dto/chat";
import type { PendingChatUnlockKind } from "@/lib/navigation/chat_unlock_session";
import type { ChatLockType } from "@/data/schemas/chat";
import type { PendingChatPromotion } from "@/data/storage/navigation";
import type { ChatPromotionState } from "./helper/promotion";

export type ChatUpgradeReason = "insufficient_credits";

export interface ChatUnlockPaywallRequest {
  displayMessageId: string;
  messageId?: string;
  kind: PendingChatUnlockKind;
  lockType?: ChatLockType;
  clientLockId?: string;
  promotion?: PendingChatPromotion;
  reason: string;
  creditBalance: number;
  requiredCredits: number;
  shortfallCredits: number;
}

export interface ChatState {
  messages: UiMessage[];
  promotion: ChatPromotionState | null;
  isReplyingAI: boolean;
  pendingReplyCount: number;
  upgradePromptVisible: boolean;
  upgradeReason: ChatUpgradeReason | null;
  canSendMessage: boolean;
  creditBalance: number;
  creditsCharged: number;
  requiredCredits: number;
  shortfallCredits: number;
  /** history 首屏可展示标志（本地快照加载完成即可进入 ready）。 */
  historyLoaded: boolean;
  paymentUnlockPending: boolean;
  unlockHistoryPromptVisible: boolean;
  lockedHistoryCount: number;
  isUnlockingHistory: boolean;
  unlockHistoryError: string | null;
  isUnlockingMessage: boolean;
  unlockingMessageId: string | null;
  unlockingMessageKind: PendingChatUnlockKind | null;
  unlockingRemoteMessageId: string | null;
  unlockingLockType: ChatLockType | null;
  unlockingClientLockId: string | null;
  unlockMessageError: string | null;
  unlockPaywallRequest: ChatUnlockPaywallRequest | null;
}

export const initialState: ChatState = {
  messages: [],
  promotion: null,
  isReplyingAI: false,
  pendingReplyCount: 0,
  upgradePromptVisible: false,
  upgradeReason: null,
  canSendMessage: true,
  creditBalance: 0,
  creditsCharged: 0,
  requiredCredits: 0,
  shortfallCredits: 0,
  historyLoaded: false,
  paymentUnlockPending: false,
  unlockHistoryPromptVisible: false,
  lockedHistoryCount: 0,
  isUnlockingHistory: false,
  unlockHistoryError: null,
  isUnlockingMessage: false,
  unlockingMessageId: null,
  unlockingMessageKind: null,
  unlockingRemoteMessageId: null,
  unlockingLockType: null,
  unlockingClientLockId: null,
  unlockMessageError: null,
  unlockPaywallRequest: null,
};
