"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 allTasks = await db_1.db.select().from(schema_1.tasks).orderBy((0, drizzle_orm_1.desc)(schema_1.tasks.dueDate));
        res.json(allTasks);
    }
    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 newTask = {
            ...req.body,
            id,
            createdAt: new Date(),
            status: req.body.status || 'pending'
        };
        await db_1.db.insert(schema_1.tasks).values(newTask);
        (0, socket_instance_1.getIO)().emit("task_created", newTask);
        res.json(newTask);
    }
    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.tasks).set(req.body).where((0, drizzle_orm_1.eq)(schema_1.tasks.id, id));
        const updated = await db_1.db.select().from(schema_1.tasks).where((0, drizzle_orm_1.eq)(schema_1.tasks.id, id));
        (0, socket_instance_1.getIO)().emit("task_updated", updated[0]);
        res.json(updated[0]);
    }
    catch (error) {
        console.error(error);
        res.status(500).json({ error: "Server error" });
    }
});
router.delete("/:id", auth_1.authenticateToken, async (req, res) => {
    try {
        const { id } = req.params;
        await db_1.db.delete(schema_1.tasks).where((0, drizzle_orm_1.eq)(schema_1.tasks.id, id));
        (0, socket_instance_1.getIO)().emit("task_deleted", { id });
        res.json({ success: true });
    }
    catch (error) {
        console.error(error);
        res.status(500).json({ error: "Server error" });
    }
});
exports.default = router;
