const express = require('express');
const router = express.Router();
const pool = require('../db');
const requireOrgPermission = require('../middleware/requireOrgPermission');
const verifyClientToken = require('../middleware/authClient');


router.get('/', verifyClientToken, async (req, res) => {
  try {
    // ✅ FIXED auth fields
    const userId = req.user.userId;
    const organizationId = req.user.organizationId;

    // ---- projectId (required)
    const projectIdRaw = req.query.projectId;
    const projectId = Number(projectIdRaw);

    if (!projectIdRaw || Number.isNaN(projectId)) {
      return res.status(400).json({ error: 'projectId required' });
    }

    // ---- roomId (optional, default = 0)
    const roomIdRaw = req.query.roomId;
    const roomId = roomIdRaw === undefined ? 0 : Number(roomIdRaw);

    if (Number.isNaN(roomId)) {
      return res.status(400).json({ error: 'roomId invalid' });
    }

    const limit = Math.min(Number(req.query.limit) || 30, 100);
    const before = req.query.before || null;

    // ✅ SINGLE project membership check
    const [member] = await pool.query(
      `
      SELECT 1
      FROM project_users
      WHERE projectId = ?
        AND userId = ?
        AND organizationId = ?
      LIMIT 1
      `,
      [projectId, userId, organizationId]
    );

    if (!member.length) {
      return res.status(403).json({ error: 'Not a member of this project' });
    }

    /* ----------------------------------
       UNIFIED TIMELINE QUERY
    ----------------------------------- */
    const params = [
      organizationId, projectId, roomId,
      ...(before ? [before] : []),
      organizationId, projectId, roomId,
      ...(before ? [before] : []),
      limit
    ];

    const sql = `
      (
        SELECT
          id,
          sender_id,
          message,
          NULL AS filepath,
          filename,
          is_file,
          reply_to_id,
          timestamp,
          'message' AS item_type
        FROM project_room_messages
        WHERE organizationId = ?
          AND projectId = ?
          AND roomId = ?
          ${before ? 'AND timestamp < ?' : ''}
      )
      UNION ALL
      (
        SELECT
          id,
          sender_id,
          NULL AS message,
          filepath,
          filename,
          1 AS is_file,
          NULL AS reply_to_id,
          timestamp,
          'file' AS item_type
        FROM project_room_files
        WHERE organizationId = ?
          AND projectId = ?
          AND roomId = ?
          ${before ? 'AND timestamp < ?' : ''}
      )
      ORDER BY timestamp DESC
      LIMIT ?
    `;

    const [rows] = await pool.query(sql, params);

    rows.reverse(); // send ASC to frontend

    res.json({
      items: rows,
      nextCursor: rows.length ? rows[0].timestamp : null
    });

  } catch (err) {
    console.error('[PROJECT ROOM HISTORY ERROR]', err);
    res.status(500).json({ error: 'Failed to load history' });
  }
});


module.exports = router;
