// sockets/chat.socket.js
const pool = require('../db');

function projectRoom(orgId, projectId) {
  return `org:${orgId}:project:${projectId}`;
}

module.exports = function initChatSockets(io, socket) {
  if (!pool?.query) {
    console.error('DB pool not initialized in chat.socket.js');
    return;
  }


  const { userId, orgId } = socket.user;

  /* ---------------------------
     AVATAR UPDATED (ORG-WIDE)
  ---------------------------- */
  socket.on('avatar_updated', ({ avatar }) => {
    if (!avatar) return;

    io.to(`org:${orgId}`).emit('avatar_updated', {
      userId,
      avatar
    });
  });

  /* ---------------------------
     SEND MESSAGE (ALL CHAT)
---------------------------- */
socket.on('send_message', async (data) => {
  console.log('SERVER send_message received:', data);

  let {
    mode,
    receiverId = null,
    projectId = null,
    roomId = null,
    message,
    tempId = null,
    is_file = 0,
    filename = null,
    reply_to_id = null
  } = data;

  if (!message) return;

  try {

    /* ======================================================
       CODE BLOCK DETECTION (SERVER SIDE)
    ====================================================== */
    let isCode = false;

    if (
      typeof message === 'string' &&
      message.startsWith('<code>') &&
      message.endsWith('</code>')
    ) {
      isCode = true;

      // Strip wrapper tags
      message = message
        .replace(/^<code>/, '')
        .replace(/<\/code>$/, '');
    }

    /* ======================================================
       PROJECT ROOM MESSAGE
    ====================================================== */
    if (mode === 'project-room') {
      if (!projectId) {
        console.warn('Project-room message missing projectId', data);
        return;
      }

      const [result] = await pool.query(
        `
        INSERT INTO project_room_messages
        (organizationId, projectId, roomId, sender_id, message, is_file, filename, reply_to_id)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        `,
        [
          orgId,
          projectId,
          roomId,
          userId,
          message,
          is_file,
          filename,
          reply_to_id
        ]
      );

      const savedMessage = {
        id: result.insertId,
        organizationId: orgId,
        projectId,
        roomId,
        senderId: userId,

        message,
        is_file,
        isCode,        // ✅ added

        filename,
        reply_to_id,
        tempId,
        timestamp: Date.now()
      };

      const room = projectRoom(orgId, projectId);
      console.log('[PROJECT ROOM EMIT]', room);

      io.to(room).emit('receive_message', savedMessage);
      return;
    }

    /* ======================================================
       DIRECT USER MESSAGE
    ====================================================== */
    if (receiverId) {
      const [result] = await pool.query(
        `
        INSERT INTO messages
        (organizationId, sender_id, receiver_id, message, is_file, filename, reply_to_id)
        VALUES (?, ?, ?, ?, ?, ?, ?)
        `,
        [
          orgId,
          userId,
          receiverId,
          message,
          is_file,
          filename,
          reply_to_id
        ]
      );

      const savedMessage = {
        id: result.insertId,
        organizationId: orgId,
        senderId: userId,
        receiverId,

        message,
        is_file,
        isCode,        // ✅ added

        filename,
        reply_to_id,
        tempId,
        timestamp: Date.now()
      };

      io.to(`org:${orgId}`).emit('receive_message', savedMessage);
      return;
    }

    console.warn('Unhandled send_message payload:', data);

  } catch (err) {
    console.error('send_message failed:', err);
  }
});


  /* ---------------------------
     TYPING INDICATOR (ORG-WIDE)
  ---------------------------- */
  socket.on('typing', ({ receiverId }) => {
    if (!receiverId) return;

    io.to(`org:${orgId}`).emit('typing', {
      senderId: userId,
      receiverId
    });
  });

  socket.on('stop_typing', ({ receiverId }) => {
    if (!receiverId) return;

    io.to(`org:${orgId}`).emit('stop_typing', {
      senderId: userId,
      receiverId
    });
  });

 socket.on('delete_message', async (payload) => {
  try {
    console.log('DELETE PAYLOAD RAW:', payload);

    const messageId = payload?.messageId;

    console.log('DELETE REQUEST:', {
      messageId,
      socketUserId: socket.userId
    });

    if (!messageId) {
      console.warn('❌ delete_message called without messageId');
      return;
    }

    const [rows] = await pool.query(
      `SELECT id, sender_id, receiver_id, timestamp FROM messages WHERE id = ?`,
      [messageId]
    );

    console.log('MESSAGE FROM DB:', rows);

    if (!rows.length) {
      console.log('❌ Message not found');
      return;
    }

    const { sender_id, receiver_id, timestamp } = rows[0];

    // Ownership check
    if (sender_id !== socket.user.userId) {
      console.log('❌ Sender mismatch', sender_id, socket.userId);
      return;
    }

    console.log('DELETE REQUEST:', {
  messageId,
  socketUserId: socket.user?.userId
});

    // 2-minute window
    if (Date.now() - new Date(timestamp) > 120000) {
      console.log('❌ Delete window expired');
      return;
    }

    // Hard delete
    await pool.query(`DELETE FROM messages WHERE id = ?`, [messageId]);

    // Notify both users
    io.to(`user_${sender_id}`).emit('message_deleted', { messageId });
    io.to(`user_${receiver_id}`).emit('message_deleted', { messageId });

    console.log('✅ Message deleted:', messageId);

  } catch (err) {
    console.error('DELETE ERROR:', err);
  }
});


};

 
