"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const db_1 = require("../db");
const schema_1 = require("../db/schema");
const drizzle_orm_1 = require("drizzle-orm");
const auth_1 = require("../middleware/auth");
const socket_instance_1 = require("../socket-instance");
const router = (0, express_1.Router)();
router.get("/", auth_1.authenticateToken, async (req, res) => {
    try {
        const sevenDaysAgo = new Date();
        sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
        const allNotifications = await db_1.db
            .select()
            .from(schema_1.notifications)
            .where((0, drizzle_orm_1.sql) `${schema_1.notifications.createdAt} > ${sevenDaysAgo}`)
            .orderBy((0, drizzle_orm_1.desc)(schema_1.notifications.createdAt))
            .limit(15);
        res.json(allNotifications);
    }
    catch (error) {
        console.error(error);
        res.status(500).json({ error: "Server error" });
    }
});
router.post("/", auth_1.authenticateToken, async (req, res) => {
    try {
        const id = crypto.randomUUID();
        const newNotification = {
            ...req.body,
            id,
            createdAt: new Date(),
            read: false
        };
        await db_1.db.insert(schema_1.notifications).values(newNotification);
        // Emit only to specific user
        (0, socket_instance_1.getIO)().to(newNotification.userId).emit("notification_created", newNotification);
        res.json(newNotification);
    }
    catch (error) {
        console.error(error);
        res.status(500).json({ error: "Server error" });
    }
});
router.put("/:id", auth_1.authenticateToken, async (req, res) => {
    try {
        const { id } = req.params;
        await db_1.db.update(schema_1.notifications).set(req.body).where((0, drizzle_orm_1.eq)(schema_1.notifications.id, id));
        const updated = await db_1.db.select().from(schema_1.notifications).where((0, drizzle_orm_1.eq)(schema_1.notifications.id, id));
        // Emit only to specific user
        if (updated[0]) {
            (0, socket_instance_1.getIO)().to(updated[0].userId).emit("notification_updated", updated[0]);
        }
        res.json(updated[0]);
    }
    catch (error) {
        console.error(error);
        res.status(500).json({ error: "Server error" });
    }
});
exports.default = router;
