"use client";

/**
 * Payment → User / Chat 同步器
 *
 * 支付成功是跨模块事件：
 * - User 需要重新拉取 profile + entitlements，刷新 isVip / creditBalance。
 * - Chat 需要根据历史锁定消息数量决定直接解锁或弹窗确认。
 */
import { useEffect, useRef } from "react";

import { useChatDispatch } from "@/stores/chat/chat-context";
import { useUserDispatch } from "@/stores/user/user-context";

import { usePaymentState } from "./payment-context";

export function PaymentSuccessSync() {
  const paymentState = usePaymentState();
  const userDispatch = useUserDispatch();
  const chatDispatch = useChatDispatch();
  const lastPaidKeyRef = useRef<string | null>(null);

  useEffect(() => {
    if (!paymentState.isPaid || !paymentState.currentOrderId) return;

    const paidKey = `${paymentState.currentOrderId}:${paymentState.orderStatus}`;
    if (lastPaidKeyRef.current === paidKey) return;
    lastPaidKeyRef.current = paidKey;

    userDispatch({ type: "UserFetch" });
    chatDispatch({ type: "ChatPaymentSucceeded" });
  }, [
    chatDispatch,
    paymentState.currentOrderId,
    paymentState.isPaid,
    paymentState.orderStatus,
    userDispatch,
  ]);

  return null;
}
