const express = require('express');
const nodemailer = require("nodemailer");
const router = express.Router();
const pool = require("../db");
require("dotenv").config();


const BASE_URL = process.env.BASE_URL;

router.get("/contact", async (req, res) => {
    try {
        // Get the contacts query
        const contactsQuery = `SELECT * FROM social_media WHERE name IN ('instagram', 'gmail', 'linkedin');`;

        // Perform query
        const contacts = await pool.query(contactsQuery);

        // Ensure contacts is an array before using .map()
        if (Array.isArray(contacts)) {
            // Append URL to logo if needed, only if logo is not null
            const updatedContacts = contacts.map(contact => {
                // Check if logo is not null
                if (contact.logo) {
                    contact.logo = BASE_URL + contact.logo; // prepend the base URL
                }
                return contact;
            });

            // Send the updated contacts data
            res.json(updatedContacts);
        } else {
            throw new Error('Contacts data is not an array');
        }

    } catch (err) {
        console.error("Error fetching contact data:", err.message);
        res.status(500).send("Server error");
    }
});

router.post("/send", async (req, res) => {
    const { name, email, message } = req.body;
  
    if (!name || !email || !message) {
      return res.status(400).json({ error: "All fields are required." });
    }
  
    const transporter = nodemailer.createTransport({
      service: "gmail",
      auth: {
        user: process.env.EMAIL_USER,
        pass: process.env.EMAIL_PASS,
      },
    });
  
    const mailOptions = {
      from: email,
      to: process.env.EMAIL_USER,
      subject: `New Message from ${name}`,
      text: `From: ${name}\nEmail: ${email}\n\nMessage:\n${message}`,
    };
  
    const mailConfirm = {
      from: process.env.EMAIL_USER,
      to: email,
      subject: "Message Received",
      text: "Your message was received, I will contact you as soon as possible!",
    };
  
    try {
      // Respond to the frontend immediately
      res.status(200).json({ success: "Message sent successfully!" });
  
      // Send emails asynchronously
      transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
          console.error("Error sending contact email:", error);
        } else {
          console.log("Contact email sent: %s", info.messageId);
        }
      });
  
      transporter.sendMail(mailConfirm, (error, info) => {
        if (error) {
          console.error("Error sending confirmation email:", error);
        } else {
          console.log("Confirmation email sent: %s", info.messageId);
        }
      });
    } catch (error) {
      console.error("Error:", error);
      res.status(500).json({ error: "Failed to send message." });
    }
  });


module.exports = router;
