// sockets/services/projectRoomService.js

const { PROJECT_ROOM_EVENTS } = require('../projectRooms.events');
const { buildProjectRoomName } = require('../../utils/socketGuards');
const { insertRoomMessage } = require('./projectRoomMessageRepo');

const {
  isUserInProjectRoom,
  isRoomArchived
} = require('./projectRoomMembership');

async function handleEnterRoom(io, socket, payload) {
  try {
    if (!payload || !payload.projectId || !payload.roomId) {
      return socket.emit(PROJECT_ROOM_EVENTS.ERROR, {
        code: 'INVALID_PAYLOAD',
        message: 'projectId and roomId are required'
      });
    }

    const { userId, orgId } = socket.user;
    const { projectId, roomId } = payload;

    const isMember = await isUserInProjectRoom(userId, projectId, orgId);

    if (!isMember) {
      return socket.emit(PROJECT_ROOM_EVENTS.ERROR, {
        code: 'NOT_AUTHORIZED',
        message: 'User not a member of this room'
      });
    }

const archived = await isRoomArchived(projectId);
    if (archived) {
      return socket.emit(PROJECT_ROOM_EVENTS.ERROR, {
        code: 'ROOM_ARCHIVED',
        message: 'Room is archived'
      });
    }

    const roomName = buildProjectRoomName({ orgId, projectId, roomId });

    socket.join(roomName);

    socket.emit(PROJECT_ROOM_EVENTS.ENTERED, {
      roomId,
      projectId
    });

  } catch (err) {
    console.error('[PROJECT ROOM ENTER ERROR]', err);
    socket.emit(PROJECT_ROOM_EVENTS.ERROR, {
      code: 'INTERNAL_ERROR',
      message: 'Failed to enter room'
    });
  }
}

async function handleLeaveRoom(io, socket, payload) {
  try {
    if (!payload || !payload.projectId || !payload.roomId) {
      return;
    }

    const { orgId } = socket.user;
    const { projectId, roomId } = payload;

    const roomName = buildProjectRoomName({ orgId, projectId, roomId });

    socket.leave(roomName);

    socket.emit(PROJECT_ROOM_EVENTS.LEFT, {
      roomId,
      projectId
    });

  } catch (err) {
    console.error('[PROJECT ROOM LEAVE ERROR]', err);
  }
}

async function handleSendMessage(io, socket, payload) {
  try {

    if (!payload || !payload.projectId || !payload.roomId || !payload.message) {
      return socket.emit('project_room:error', {
        code: 'INVALID_PAYLOAD',
        message: 'Missing required fields'
      });
    }

    const { userId, orgId } = socket.user;
    const { projectId, roomId, message, replyToId } = payload;

    // 🔒 Reuse authorization
    const isMember = await isUserInProjectRoom(userId, projectId, orgId);
    if (!isMember) {
      return socket.emit('project_room:error', {
        code: 'NOT_AUTHORIZED',
        message: 'User not in room'
      });
    }
    
    const archived = await isRoomArchived(roomId);
    if (archived) {
      return socket.emit('project_room:error', {
        code: 'ROOM_ARCHIVED',
        message: 'Room is archived'
      });
    }    

    // 🧠 Insert message
    const savedMessage = await insertRoomMessage({
      organizationId: orgId,
      projectId,
      roomId,
      sender_id: userId,
      message,
      reply_to_id: replyToId
    });

    const roomName = buildProjectRoomName({ orgId, projectId, roomId });

    // 📣 Broadcast to room
    io.to(roomName).emit('project_room:message', savedMessage);

  } catch (err) {
    console.error('[PROJECT ROOM SEND ERROR]', err);
    socket.emit('project_room:error', {
      code: 'INTERNAL_ERROR',
      message: 'Failed to send message'
    });
  }
}


module.exports = {
  handleEnterRoom,
  handleLeaveRoom,
  handleSendMessage
};
