"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 db_1 = require("../db");
const schema_1 = require("../db/schema");
const drizzle_orm_1 = require("drizzle-orm");
const auth_1 = require("../middleware/auth");
const bcryptjs_1 = __importDefault(require("bcryptjs"));
const socket_instance_1 = require("../socket-instance");
const router = (0, express_1.Router)();
// Get all users
router.get("/", auth_1.authenticateToken, async (req, res) => {
    try {
        const allUsers = await db_1.db.select({
            id: schema_1.users.id,
            email: schema_1.users.email,
            name: schema_1.users.name,
            role: schema_1.users.role,
            avatar: schema_1.users.avatar,
            createdAt: schema_1.users.createdAt
        }).from(schema_1.users);
        res.json(allUsers);
    }
    catch (error) {
        console.error(error);
        res.status(500).json({ error: "Server error" });
    }
});
// Update user
router.put("/:id", auth_1.authenticateToken, async (req, res) => {
    try {
        const { id } = req.params;
        const { password, ...updateData } = req.body;
        if (password) {
            updateData.password = await bcryptjs_1.default.hash(password, 10);
        }
        await db_1.db.update(schema_1.users).set(updateData).where((0, drizzle_orm_1.eq)(schema_1.users.id, id));
        const userList = await db_1.db.select({
            id: schema_1.users.id,
            email: schema_1.users.email,
            name: schema_1.users.name,
            role: schema_1.users.role,
            avatar: schema_1.users.avatar
        }).from(schema_1.users).where((0, drizzle_orm_1.eq)(schema_1.users.id, id)).limit(1);
        if (userList.length === 0) {
            return res.status(404).json({ error: "User not found" });
        }
        const updatedUser = userList[0];
        // Emit real-time event
        (0, socket_instance_1.getIO)().emit("user_updated", updatedUser);
        res.json(updatedUser);
    }
    catch (error) {
        console.error(error);
        res.status(500).json({ error: "Server error" });
    }
});
// Delete user
router.delete("/:id", auth_1.authenticateToken, async (req, res) => {
    try {
        const { id } = req.params;
        // Prevent self-deletion
        if (id === req.user?.id) {
            return res.status(400).json({ error: "Cannot delete yourself" });
        }
        await db_1.db.delete(schema_1.users).where((0, drizzle_orm_1.eq)(schema_1.users.id, id));
        // Emit real-time event
        (0, socket_instance_1.getIO)().emit("user_deleted", { id });
        res.json({ success: true });
    }
    catch (error) {
        console.error(error);
        res.status(500).json({ error: "Server error" });
    }
});
exports.default = router;
