import axios from "axios";
const Imap = require ("imap");
import  {simpleParser }   from "mailparser";

interface response {
  "subject": string,
  "from": string,
  "date": string,
  "textBody": string,
  "htmlBody": boolean|string
}

export const createEmailCpanel = async (
  {
    domain,
    email,
    password,
    quota,
  }: { domain: string; email:string; password:string; quota:string },
  auth:{
    password:string,
    username:string,
    cpanelHost:string
  }
) => {
  const apiEndpoint = `https://${auth.cpanelHost}:2083/execute/Email/add_pop`;

  try {
    const response = await axios.post(
      apiEndpoint,
      { domain, email, password, quota: quota || 100 },
      {
        auth,
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
      }
    );

    return response.data;
  } catch (error:any) {
    throw new Error(error.message);
  }
};

//create to delete email
export const deleteEmailCpanel = async (
  {
    domain,
    email,
  }: { domain: string; email:string; },
  auth:{
    password:string,
    username:string,
    cpanelHost:string
  }
) => {
  const apiEndpoint = `https://${auth.cpanelHost}:2083/execute/Email/delete_pop`;

  try {
    const response = await axios.post(
      apiEndpoint,
      { domain, email },
      {
        auth,
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
      }
    );

    return response.data;
  } catch (error:any) {
    throw new Error(error.message);
  }
};


//read emails sent and resend
export const listEmailsCpanel = async (
  {
    domain,
  }: { domain: string; },
  auth:{
    password:string,
    username:string,
    cpanelHost:string
  }
) => {
  const apiEndpoint = `https://${auth.cpanelHost}:2083/execute/Email/list_pops`;

  try {
    const response = await axios.post(
      apiEndpoint,
      { domain },
      {
        auth,
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
      }
    );

    return response.data;
  } catch (error:any) {
    throw new Error(error.message);
  }
};

//fetch email

export const fetchEmail = async (
  {
    domain,
    email,
    password,
    folder,
  }: { domain: string; email: string; password: string,folder:string }
) => {
  try {
    const emails = await fetchEmails("INBOX", {
      user: `${email}@${domain}`,
      password,
      host: domain, // Replace with your IMAP server
      port: 993,
      tls: true,
      tlsOptions: { rejectUnauthorized: false },
    });

    console.log("emails",emails)
    return emails as response[];
  } catch (error: any) {
    throw new Error(error.message);
  }
};


function fetchEmails(folder = "INBOX", imapConfig:any) {
  return new Promise((resolve, reject) => {
    const imap = new Imap(imapConfig);
    const emails: any[] = [];

    imap.once("ready", function () {
      console.log("IMAP connection established");
      imap.getBoxes((err, boxes) => {
        if (err) console.error("Error listing folders:", err);
        else console.log("Available folders:", boxes);
      });
      imap.openBox(folder, true, function (err, box) {
        if (err) {
          reject(`Error opening folder: ${err}`);
          return;
        }

        console.log("Folder opened:", folder);

        imap.search(["ALL"], function (err, results) {
          if (err) {
            reject(`Error searching emails: ${err}`);
            return;
          }

          if (!results || results.length === 0) {
            console.log("No emails found");
            resolve([]);
            imap.end();
            return;
          }

          console.log("Found emails:", results.length);

          const f = imap.fetch(results, { bodies: "" });

          f.on("message", function (msg, seqno) {
            msg.on("body", function (stream:any, info) {
              simpleParser(stream, (err, parsed) => {
                if (err) {
                  console.error("Error parsing email:", err);
                  return;
                }

                const email = {
                  subject: parsed.subject,
                  from: parsed.from?.text,
                  date: parsed.date,
                  textBody: parsed.text,
                  htmlBody: parsed.html,
                };

                console.log("Parsed email:", email);
                emails.push(email);
              });
            });
          });

          f.once("error", function (err) {
            reject(`Fetch error: ${err}`);
          });

          f.once("end", function () {
            console.log("Done fetching all messages!");
            imap.end();
          });
        });
      });
    });

    imap.once("error", function (err:any) {
      reject(`IMAP error: ${err}`);
    });

    imap.once("end", function () {
      console.log("IMAP connection closed.");
      resolve(emails);
    });

    imap.connect();
  });
}


