import prismadb from "@/lib/prisma";
import { Order, Status } from "@prisma/client";
const nodemailer = require("nodemailer");
import fs from 'fs';

//config du serveur d'envoie su mail
const transporter = nodemailer.createTransport({
  host: process.env.EMAIL_HOST,
  port: process.env.EMAIL_PORT,
  secure: true,
  auth: {
    user: process.env.MY_EMAIL,
    pass: process.env.MY_PASSWORD,
  },
});

//fonction pour lire le contenu du fichier PDF
const readPDFFile = (filePath: string) => {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
};

//signature du mail
const getEmailFooter = (storeInfo: any) => {
  return `
    <table style="border-collapse: collapse;">
      <tr>
        <td style="border: none;">${storeInfo?.logo ? `<img src="cid:logo" alt="Logo de la boutique" style="max-width: 100px;">` : ''}</td>
        <td style="border: none; vertical-align: top;">
          <p><b>Contact :</b></p>
            ${storeInfo?.shopMail ? `Mail : <a href="mailto:${storeInfo?.shopMail}">${storeInfo?.shopMail}</a><br>` : ''}
            ${storeInfo?.shopUrl ? `Site internet : <a href="https://${storeInfo?.shopUrl}">${storeInfo?.shopUrl}</a><br>` : ''}
            ${storeInfo?.shopPhone ? `Téléphone : <a href="tel:${storeInfo?.shopPhone}">${storeInfo?.shopPhone}</a>` : ''}
        </td>
      </tr>
    </table>
    <p>Powered by <a href="https://projoctopus.com">ProjOctopus 🐙</a></p>  
  `
}

//mail de confirmation d'envoie de la commande
export const envoieMailConfirmationCommande = async (storeId: string, order: Order, statutId: string, orderURL: string) => {
  const mailInfo = await prismadb.mailInfo.findFirst({
    where: {
      storeId
    }
  });

  //récup info du statut utilisé
  const statutInfo = await prismadb.status.findUnique({
    where: {
      id: statutId,
    }
  });

  //récup des informations de la boutique
  const storeInfo = await prismadb.store.findFirst({
    where: {
      id: storeId
    }
  })

  //supp de la partie 'data:image/jpeg;base64,' de l'URL de l'image
  let base64Image = storeInfo?.logo.split(';base64,').pop();

  //pièces jointes
  let attachments = [];
  if (base64Image) {
    attachments.push({
      cid: "logo",
      filename: 'logo.jpeg',
      content: Buffer.from(storeInfo?.logo ? base64Image : "", 'base64'),
      encoding: 'base64'
    });
  }

  //contenu HTML de l'e-mail
  let emailContent = `
    <html>
    <body>
      <p>Bonjour ${order.firstName},</p>
      <p>${statutInfo?.emailBody}</p>
      <p>Retrouvez votre confirmation sur <a href="${orderURL}">notre site internet.</a></p>
    </body>
    </html>
  `;

  const emailFooter = getEmailFooter(storeInfo);

  //construction et envoie du mail
  return await transporter.sendMail({
    from: `"${mailInfo?.printUsername}" <${process.env.MY_EMAIL}>`,
    to: order.email,
    subject: `${statutInfo?.emailSubject} #${order.reference}`,
    html: emailContent + emailFooter,
    attachments: attachments
  });
}

//mail information vendeur nouvelle commande
export const envoieMailInformationVendeur = async (storeId: string, order: Order) => {
  const mailInfo = await prismadb.mailInfo.findFirst({
    where: {
      storeId
    }
  });

  //récup des informations de la boutique
  const storeInfo = await prismadb.store.findFirst({
    where: {
      id: storeId
    }
  });

  let emailContent = `
    <html>
    <body>
      <p>Une nouvelle commande a été effectuée sur la boutique ${storeInfo?.shopUrl}</p>
      <p>Type de paiement : "${order?.paymentMethodName}"</p>
      <p>Montant : "${order?.amount}" €</p>
    </body>
    </html>
  `;

  //construction et envoie du mail
  return await transporter.sendMail({
    from: `"${mailInfo?.printUsername}" <${process.env.MY_EMAIL}>`,
    to: storeInfo?.shopMail,
    subject: `Nouvelle commande ! #${order?.reference}`,
    html: emailContent
  });
}

//mail de confirmation d'envoie de la commande
export const envoieMailChangementStatus = async (storeId: string, orderId: string, statut: Status, invoiceReference?: string) => {
  const mailInfo = await prismadb.mailInfo.findFirst({
    where: {
      storeId
    }
  });

  //récup info de la commande
  const order = await prismadb.order.findUnique({
    where: {
      id: orderId,
    }
  });

  //récup des informations de la boutique
  const storeInfo = await prismadb.store.findFirst({
    where: {
      id: storeId
    }
  })

  //supp de la partie 'data:image/jpeg;base64,' de l'URL de l'image
  let base64Image = storeInfo?.logo.split(';base64,').pop();

  //pièces jointes
  let attachments = [];
  if (base64Image) {
    attachments.push({
      cid: "logo",
      filename: 'logo.jpeg',
      content: Buffer.from(storeInfo?.logo ? base64Image : "", 'base64'),
      encoding: 'base64'
    });
  }

  //envoie de la facture si statut est payé ou génération facture
  if (statut.id == "2dbe2055-b3b4-4172-9b5b-af93670dcca8" || statut.id == "2dbe2055-b3b4-4172-9b5b-af93670dcca3") {
    invoiceReference = invoiceReference + ".pdf";
    //chemin
    const filePath = "./../documents/" + storeId + "/factures/" + invoiceReference;

    const pdfContent = await readPDFFile(filePath);
    attachments.push({
      cid: "facture",
      filename: invoiceReference,
      content: pdfContent,
      encoding: 'base64'
    });
  }

  //contenu HTML de l'e-mail
  let emailContent = `
    <html>
    <body>
      <p>Bonjour ${order?.firstName},</p>
      <p>${statut.emailBody}</p>
      <p>Retrouvez votre commande dans votre espace personnel de notre site internet.</p>
    </body>
    </html>
  `;

  const emailFooter = getEmailFooter(storeInfo);

  //construction et envoie du mail
  return await transporter.sendMail({
    from: `"${mailInfo?.printUsername}" <${process.env.MY_EMAIL}>`,
    to: order?.email,
    subject: `${statut.emailSubject} #${order?.reference}`,
    html: emailContent + emailFooter,
    attachments: attachments
  });
}