import { Request, Response, NextFunction } from 'express';
import ConversationModel from '../../models/Conversation';
import { getRoomKeyForUsers } from '../../lib/chat-helper';
import { UniResponse } from '../../lib/UniResponse';
import { asyncHandler } from '../../utils/asyncHandler';
import mongoose from 'mongoose';

interface AuthenticatedRequest extends Request {
  user?: {
    userId: string;
    email: string;
    role: string;
  };
}

export class SocketController {
  public static joinRoom = asyncHandler(
    async (
      req: AuthenticatedRequest,
      res: Response,
      _next: NextFunction
    ): Promise<void> => {
      const myId = req.user?.userId;
      const { otherUserId, scan_id } = req.body as {
        otherUserId?: string;
        scan_id?: string;
      };

      if (!myId || !otherUserId) {
        const response = UniResponse.Error('Missing userId or otherUserId', null, 400);
        res.status(response.code).json(response);
        return;
      }

      const a = String(myId);
      const b = String(otherUserId);
      const participants = [a, b];

      // Find or create conversation by participants AND scan_id.
      // This ensures that different scans (e.g. Car vs Medical) have separate chat rooms.
      const scanObjectId = scan_id ? new mongoose.Types.ObjectId(scan_id) : null;

      let conversation = await ConversationModel.findOne({
        participants: { $all: participants, $size: 2 },
        scan_id: scanObjectId,
      });

      if (!conversation) {
        if (!scanObjectId) {
          const response = UniResponse.Error(
            'scan_id is required to create a scan-scoped conversation',
            null,
            400
          );
          res.status(response.code).json(response);
          return;
        }
        conversation = await ConversationModel.create({
          participants,
          scan_id: scanObjectId,
          anonymous: false,
        });
        console.log(
          'join_room (HTTP): Created new conversation:',
          conversation._id,
          'for scan:',
          scan_id
        );
      }

      // We can still include scan_id in the room key / response if provided,
      // but it will not affect the conversation record.
      const room = getRoomKeyForUsers(a, b, scan_id);

      const response = UniResponse.Success('Room prepared successfully', {
        conversation_id: String(conversation._id),
        room,
        participants,
        scan_id,
      });

      res.status(response.code).json(response);
    }
  );
}
