import express from 'express';
import { authenticate } from '../middlewares/auth/authMiddleware.js';
import { db } from '../config/database.js';
import { users } from '../db/schema.js';
import { eq } from 'drizzle-orm';

const router = express.Router();

// All user routes require authentication
router.use(authenticate);

/**
 * Get all users (basic info only - for dropdowns, assignment, etc.)
 * Available to all authenticated users
 */
router.get('/', async (req, res, next) => {
  try {
    const allUsers = await db
      .select({
        id: users.id,
        username: users.username,
        firstName: users.firstName,
        lastName: users.lastName,
        role: users.role,
        lastSeen: users.lastSeen,
      })
      .from(users)
      .orderBy(users.username);

    res.json(allUsers);
  } catch (error) {
    next(error);
  }
});

/**
 * Update user's lastSeen timestamp (heartbeat)
 * POST /api/users/heartbeat
 */
router.post('/heartbeat', async (req, res, next) => {
  try {
    const userId = req.userId;

    await db
      .update(users)
      .set({ lastSeen: new Date() })
      .where(eq(users.id, userId));

    res.json({ success: true });
  } catch (error) {
    next(error);
  }
});

export default router;
