const express = require('express');
const router = express.Router();

const verifyClientToken = require('../middleware/authClient');
const serializeMessage = require('../utils/messageSerializer');

module.exports = ({ pool }) => {

  /* ======================================================
     DIRECT CHAT HISTORY
     /api/chat/history?otherUserId=2
  ====================================================== */
  router.get('/', verifyClientToken, async (req, res) => {
    try {

      const userId = req.user.userId;
      const organizationId = req.user.organizationId;
      const otherUserId = Number(req.query.otherUserId);

      if (!otherUserId) {
        return res.status(400).json({ success: false, message: 'otherUserId required' });
      }

      const protocol = req.headers['x-forwarded-proto'] || req.protocol;
      const host = req.get('host');
      const baseUrl = process.env.BASE_URL || `${protocol}://${host}`;

      const [rows] = await pool.query(
        `
        SELECT
          m.id,
          m.sender_id,
          m.receiver_id,
          m.message,
          m.is_file,
          m.filename,
          f.filepath,
          m.timestamp
        FROM messages m
        LEFT JOIN files f
          ON f.message_id = m.id
        WHERE m.organizationId = ?
          AND (
            (m.sender_id = ? AND m.receiver_id = ?)
            OR
            (m.sender_id = ? AND m.receiver_id = ?)
          )
        ORDER BY m.timestamp ASC
        `,
        [
          organizationId,
          userId,
          otherUserId,
          otherUserId,
          userId
        ]
      );

      const items = rows.map(row =>
        serializeMessage(row, { baseUrl })
      );

      res.json({ success: true, items });

    } catch (err) {
      console.error('DIRECT CHAT HISTORY ERROR:', err);
      res.status(500).json({ success: false });
    }
  });

  /* ======================================================
     PROJECT ROOM HISTORY
     /api/chat/history/project
  ====================================================== */
  router.get('/project', verifyClientToken, async (req, res) => {
    try {

      const organizationId = req.user.organizationId;
      const projectId = Number(req.query.projectId);
      const roomId = Number(req.query.roomId);

      if (!projectId || !roomId) {
        return res.status(400).json({ success: false });
      }

      const protocol = req.headers['x-forwarded-proto'] || req.protocol;
      const host = req.get('host');
      const baseUrl = process.env.BASE_URL || `${protocol}://${host}`;

      const [rows] = await pool.query(
        `
        SELECT
          prm.id,
          prm.sender_id,
          prm.projectId,
          prm.roomId,
          prm.message,
          prm.is_file,
          prm.filename,
          f.filepath,
          prm.timestamp
        FROM project_room_messages prm
        LEFT JOIN files f
          ON f.project_message_id = prm.id
        WHERE prm.organizationId = ?
          AND prm.projectId = ?
          AND prm.roomId = ?
        ORDER BY prm.timestamp ASC
        `,
        [
          organizationId,
          projectId,
          roomId
        ]
      );

      const items = rows.map(row =>
        serializeMessage(row, { baseUrl })
      );

      res.json({ success: true, items });

    } catch (err) {
      console.error('PROJECT ROOM HISTORY ERROR:', err);
      res.status(500).json({ success: false });
    }
  });

  return router;
};
