import { API_BASE_URL } from "../config/api";
import { getAccessToken } from "../utils/auth";

export interface InboxMessage {
  user_id: string;
  Message: string;
  title: string;
  status: string; // "خوانده نشده" | "خوانده شده"
  kind: string; // "موفقیت" | "خبر" | "اخطار" | "پیشنهاد" | "عادی"
  stageID: number;
}

export interface InboxResponse {
  inbox: InboxMessage[];
  unreadCount: number;
}

export const loadInbox = async (): Promise<InboxResponse> => {
  const token = getAccessToken();
  if (!token) {
    return { inbox: [], unreadCount: 0 };
  }

  try {
    const response = await fetch(`${API_BASE_URL}/api/call`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
        "Authorization": `Bearer ${token}`,
      },
      body: JSON.stringify({
        get_inbox_function: {},
      }),
    });

    const result = await response.json();

    if (result.state === 0 && result.data) {
      const parsedData = JSON.parse(result.data);
      const inbox: InboxMessage[] = parsedData.inbox ? JSON.parse(parsedData.inbox) : [];

      // Count unread messages
      const unreadCount = inbox.filter((msg) => msg.status === "خوانده نشده").length;

      return { inbox, unreadCount };
    }

    return { inbox: [], unreadCount: 0 };
  } catch (error) {
    console.error("Error loading inbox:", error);
    return { inbox: [], unreadCount: 0 };
  }
};

export const markAsRead = async (stageIds: string[]): Promise<void> => {
  const token = getAccessToken();
  if (!token || stageIds.length === 0) {
    return;
  }

  // Fire-and-forget: فراخوانی بدون منتظر ماندن برای پاسخ
  fetch(`${API_BASE_URL}/api/call`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json;charset=UTF-8",
      "Authorization": `Bearer ${token}`,
    },
    body: JSON.stringify({
      read_inbox_function: {
        stage_ids: stageIds.join(","),
      },
    }),
  }).catch((error) => {
    console.debug("Mark as read failed:", error);
  });
};
