import express from "express";
import { authenticate } from "../../middleware/auth.js";
import { withDbSession } from "../../config/db.js";

const router = express.Router();
router.use(authenticate);

router.get("/", async (req, res, next) => {
  try {
    const data = await withDbSession(req.user, async (db) => {
      const [cases, deadlines, meetings, tasks, documents, notifications] = await Promise.all([
        db.query(`SELECT COUNT(*)::int AS count FROM br_case WHERE deleted_at IS NULL`),
        db.query(`SELECT COUNT(*)::int AS count FROM deadline WHERE deleted_at IS NULL AND due_date <= NOW() + INTERVAL '3 days'`),
        db.query(`SELECT COUNT(*)::int AS count FROM meeting WHERE meeting_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '7 days'`),
        db.query(`SELECT COUNT(*)::int AS count FROM task WHERE deleted_at IS NULL AND status <> 'erledigt'`),
        db.query(`SELECT COUNT(*)::int AS count FROM document_item WHERE deleted_at IS NULL`),
        db.query(`SELECT COUNT(*)::int AS count FROM notification_item WHERE user_id = app_user_id() AND is_read = FALSE`)
      ]);
      return {
        openCases: cases.rows[0].count,
        urgentDeadlines: deadlines.rows[0].count,
        meetingsThisWeek: meetings.rows[0].count,
        openTasks: tasks.rows[0].count,
        documents: documents.rows[0].count,
        unreadNotifications: notifications.rows[0].count,
      };
    });
    res.json(data);
  } catch (err) { next(err); }
});

export default router;
