const express = require("express");
const axios = require("axios");
const cors = require("cors");
const { OAuth2Client, UserRefreshClient } = require("google-auth-library");
const nodemailer = require("nodemailer");
const app = express();
// const mongoose = require("mongoose");

const port = 8086; // or any other available port
app.use(cors());

// Custom middleware to set Access-Control-Allow-Headers
// app.use((req, res, next) => {
//     res.setHeader(
//         "Access-Control-Allow-Headers",
//         "Authorization, Content-Type"
//     );
//     next();
// });

app.use(express.json());

// Define a route for proxying requests to the Notion API

const notionApiBaseUrl = "https://api.notion.com/v1";
const CLIENT_ID =
    "26572306564-q5opvtk1dhfndlqmiarmivpbnpu8p5oo.apps.googleusercontent.com";
const CLIENT_SECRET = "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";
const REDIRECT_URI = "http://localhost:3000/auth/google/callback";

const oAuth2Client = new OAuth2Client(CLIENT_ID, CLIENT_SECRET, "postmessage");
// Establish db connection
// const url = 'mongodb://localhost:27017/your_database_name';

// mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true })
//   .then(() => {
//     console.log('Connected to MongoDB');
//   })
//   .catch((error) => {
//     console.error('Failed to connect to MongoDB', error);
//   });

const logintonotion = () => {};

app.post("/auth/google", async (req, res) => {
    const { tokens } = await oAuth2Client.getToken(req.body.code); // exchange code for tokens
    res.json(tokens);
});

app.post("/auth/google/refresh-token", async (req, res) => {
    const user = new UserRefreshClient(
        CLIENT_ID,
        CLIENT_SECRET,
        req.body.refreshToken
    );
    const { credentials } = await user.refreshAccessToken(); // optain new tokens
    res.json(credentials);
});

app.get("/api/calendar", async (req, res) => {
    const { token } = req.query;
    // console.log(token)
    // https://www.googleapis.com/oauth2/v3/userinfo
    axios
        .get(
            `https://www.googleapis.com/calendar/v3/calendars/primary/events`,
            {
                headers: {
                    Authorization: `Bearer ${token}`,
                },
            }
        )
        .then((response) => {
            // Handle the response data
            res.status(200).json(response.data);
        })
        .catch((error) => {
            // Handle the error
            console.error(error);
        });
});

app.post("/calendar/update", (req, res) => {
    const { event, token } = req.body;
    // console.log(event);
    const calendarId = "primary";
    axios
        .post(
            `https://www.googleapis.com/calendar/v3/calendars/${calendarId}/events`,
            event,
            {
                headers: {
                    Authorization: `Bearer ${token}`,
                },
            }
        )
        .then((response) => {
            res.send(response.data);
        })
        .catch((error) => {
            console.error("Error adding even  t:", error);
        });
});

app.delete("/calendar/update", (req, res) => {
    const { eventId } = req.body;
    const { authorization } = req.headers;

    axios
        .delete(
            `https://www.googleapis.com/calendar/v3/calendars/primary/events/${eventId}`,
            {
                headers: {
                    Authorization: `Bearer ${authorization}`,
                },
            }
        )
        .then((response) => {
            res.send("Event delted !!");
        })
        .catch((error) => {
            console.error("Error deleting event:", error);
        });
});

app.get("/api/mail", async (req, res) => {
    const BASE_URL = "https://www.googleapis.com/gmail/v1";
    const userId = "me";
    const { token, pageToken, maxResults, sort, q } = req.query;
    // console.log(token)
    // https://www.googleapis.com/oauth2/v3/userinfo
    axios
        .get(`${BASE_URL}/users/${userId}/messages`, {
            headers: {
                Authorization: `Bearer ${token}`,
            },

            params: {
                maxResults: maxResults,
                pageToken: pageToken,
                sort: sort,
                q: q,
            },
        })
        .then((response) => {
            // Handle the response data
            res.status(200).json(response.data);
        })
        .catch((error) => {
            // Handle the error
            console.error(error);
        });
});

app.post("/mail/send", (req, res) => {
    const { from, to, subject, text, token } = req.body;
    // console.log(req.body)
    const transporter = nodemailer.createTransport({
        service: "gmail",
        auth: {
            type: "OAuth2",
            user: from,
            accessToken: token,
            clientId: CLIENT_ID,
            clientSecret: CLIENT_SECRET,
            // refreshToken: 'YOUR_REFRESH_TOKEN',
        },
    });

    // Compose the email options
    const mailOptions = {
        from: from,
        to: to,
        subject: subject,
        text: text,
    };

    // Send the email using Nodemailer
    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            console.error("Error sending email:", error);
            res.status(500).send("Error sending email");
        } else {
            console.log("Email sent:", info.response);
            res.send("Email sent successfully");
        }
    });
});

let notionApiConfig = {
    headers: {
        // 'Authorization': 'Bearer secret_hPk8JxZnl8CH5JBpE9M8p616rXffJZwuis64Js7udWR',
        // 'Authorization': 'Bearer secret_hPk8JxZnl8CH5JBpE9M8p616rXffJZwuis64Js7udWR',
        Authorization: "Bearer ",
        "Content-Type": "application/json",

        "Access-Control-Allow-Headers": "Authorization, Content-Type",
        "Notion-Version": "2022-06-28", // Replace with the desired API version
    },
};
let notionversionApiConfig = {
    headers: {
        // 'Authorization': 'Bearer secret_XmBzWFLLqieDawHWgnL7Cl5u4kQCKCXg1KshzrP8unI',
        Authorization: "Bearer ",
        "Content-Type": "application/json",
        "Access-Control-Allow-Headers": "Authorization, Content-Type",
        "Notion-Version": "2021-05-13", // Replace with the desired API version
    },
};

app.get("/notion/account", async (req, res) => {
    const { email, googletoken, notiontoken } = req.query;
    const { authorization } = req.headers;
    notionApiConfig.headers["Authorization"] = authorization;
    try {
        // Exchange the email for a Notion access token
        const response = await axios.get(
            "https://api.notion.com/v1/users",
            notionApiConfig
        );
        console.log(email);
        response.data.results.map((item) => {
            if (
                item.type === "person" &&
                item.person &&
                item.person.email === email
            ) {
                console.log(item.id);
                res.status(200).json(item.id);
            }
        });
    } catch (error) {
        console.error("Failed to exchange access token", error);
        res.status(500).json({ error: "Failed to exchange access token" });
    }
});

app.get("/api/notion", async (req, res) => {
    const { path, query } = req.query;
    const { authorization } = req.headers;
    notionversionApiConfig.headers["Authorization"] = authorization;
    axios
        .get(`${notionApiBaseUrl}/${path}`, notionversionApiConfig)
        .then((response) => {
            // Handle the response data
            let temparr = [];
            response.data.results.map((item, index) => {
                let values = {
                    id: item.id,
                    title: item.title[0].plain_text,
                };
                temparr.push(values);
            });
            res.status(200).json(temparr);
        })
        .catch((error) => {
            // Handle the error
            console.error(req);
        });
});

app.post("/api/notion", async (req, res) => {
    const { path, query } = req.body;
    const { authorization } = req.headers;
    // console.log(authorization);
    notionApiConfig.headers["Authorization"] = authorization;

    axios
        .post(`${notionApiBaseUrl}/${path}`, query, notionApiConfig)
        .then((response) => {
            // Handle the response data
            res.status(200).json(response.data);
        })
        .catch((error) => {
            // Handle the error
            console.error(error);
        });
});

app.patch("/api/notion", async (req, res) => {
    const { path, query } = req.body;
    const { authorization } = req.headers;
    notionApiConfig.headers["Authorization"] = authorization;
    axios
        .patch(`${notionApiBaseUrl}/${path}`, query, notionApiConfig)
        .then((response) => {
            // Handle the response data
            res.status(200).json(response.data);
        })
        .catch((error) => {
            // Handle the error
            res.status(400).json(error);
            console.error(error);
        });
});
app.get("/", (req, res) => {
    res.send("Hey, its sil");
});

// Start the server
app.listen(port, () => {
    console.log(`Server running on port ${port}`);
});
