// Task Team — Email Notifications — 2026-03-29
const nodemailer = require("nodemailer");

async function emailRoutes(app) {
    const transporter = nodemailer.createTransport({
        host: process.env.SMTP_HOST || "smtp.gmail.com",
        port: parseInt(process.env.SMTP_PORT || "587"),
        secure: false,
        auth: {
            user: process.env.SMTP_USER || "",
            pass: process.env.SMTP_PASS || ""
        }
    });

    // Send email
    app.post("/email/send", async (req) => {
        const { to, subject, text, html } = req.body;
        if (!to || !subject) throw { statusCode: 400, message: "to and subject required" };

        if (!process.env.SMTP_USER) {
            return { status: "skipped", message: "SMTP not configured" };
        }

        const info = await transporter.sendMail({
            from: process.env.SMTP_FROM || '"Task Team" <noreply@hasdo.info>',
            to, subject, text, html
        });
        return { status: "sent", messageId: info.messageId };
    });

    // Send task reminder
    app.post("/email/reminder", async (req) => {
        const { user_id, task_id } = req.body;
        const { rows: users } = await app.db.query("SELECT email, name FROM users WHERE id=$1", [user_id]);
        const { rows: tasks } = await app.db.query("SELECT title, due_at FROM tasks WHERE id=$1", [task_id]);
        if (!users.length || !tasks.length) throw { statusCode: 404, message: "User or task not found" };

        if (!process.env.SMTP_USER) return { status: "skipped", message: "SMTP not configured" };

        await transporter.sendMail({
            from: '"Task Team" <noreply@hasdo.info>',
            to: users[0].email,
            subject: `Pripominka: ${tasks[0].title}`,
            html: `<h2>Pripominka ukolu</h2><p><strong>${tasks[0].title}</strong></p><p>Termin: ${tasks[0].due_at || "bez terminu"}</p><p><a href="https://tasks.hasdo.info/tasks">Otevrit v Task Team</a></p>`
        });
        return { status: "sent" };
    });

    // Email config status
    app.get("/email/status", async () => {
        return { configured: !!process.env.SMTP_USER, host: process.env.SMTP_HOST || "not set" };
    });
}

module.exports = emailRoutes;
