import { apiFetch } from "./config";

export const loginWebmail = async (email, password) => {
  return await apiFetch("/api/webmail/login", {
    method: "POST",
    body: JSON.stringify({ email, password }),
  });
};

export const getFolders = async (email, password) => {
  const q = new URLSearchParams({ email, password });
  return await apiFetch(`/api/webmail/folders?${q.toString()}`);
};

export const getMessages = async (email, password, folder = "INBOX", page = 1, search = "") => {
  const q = new URLSearchParams({ email, password, folder, page: String(page) });
  if (search) q.append("search", search);
  return await apiFetch(`/api/webmail/messages?${q.toString()}`);
};

export const getMessageDetail = async (email, password, folder, uid) => {
  const q = new URLSearchParams({ email, password, folder, uid: String(uid) });
  return await apiFetch(`/api/webmail/message?${q.toString()}`);
};

export const sendEmail = async (email, password, to, subject, body, cc = "", bcc = "") => {
  return await apiFetch("/api/webmail/send", {
    method: "POST",
    body: JSON.stringify({
      email,
      password,
      to,
      subject,
      body,
      cc,
      bcc,
      html: body.replace(/\n/g, "<br>"),
    }),
  });
};

export const deleteMessage = async (email, password, folder, uid) => {
  return await apiFetch("/api/webmail/delete-message", {
    method: "POST",
    body: JSON.stringify({ email, password, folder, uid: String(uid) }),
  });
};

export const toggleSeen = async (email, password, folder, uid, is_seen) => {
  return await apiFetch("/api/webmail/toggle-seen", {
    method: "POST",
    body: JSON.stringify({ email, password, folder, uid: String(uid), is_seen }),
  });
};
