"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const node_crypto_1 = __importDefault(require("node:crypto"));
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 {
        console.log("Fetching activities...");
        const allActivities = await db_1.db.select({
            ...(0, drizzle_orm_1.getTableColumns)(schema_1.activities),
            userName: schema_1.users.name,
        })
            .from(schema_1.activities)
            .leftJoin(schema_1.users, (0, drizzle_orm_1.eq)(schema_1.activities.userId, schema_1.users.id))
            .orderBy((0, drizzle_orm_1.desc)(schema_1.activities.createdAt))
            .limit(10);
        console.log(`Found ${allActivities.length} activities`);
        res.json(allActivities);
    }
    catch (error) {
        console.error("Error fetching activities:", error);
        res.status(500).json({ error: "Server error" });
    }
});
router.post("/", auth_1.authenticateToken, async (req, res) => {
    try {
        const id = node_crypto_1.default.randomUUID();
        const { message, targetId, targetType, ...rest } = req.body;
        const newActivity = {
            ...rest,
            id,
            description: message || rest.description,
            entityId: targetId || rest.entityId,
            entityType: targetType || rest.entityType,
            createdAt: new Date(),
        };
        await db_1.db.insert(schema_1.activities).values(newActivity);
        // Emit activity event for real-time updates
        (0, socket_instance_1.getIO)().emit("activity_created", newActivity);
        res.json(newActivity);
    }
    catch (error) {
        console.error(error);
        res.status(500).json({ error: "Server error" });
    }
});
exports.default = router;
