import mongoose from 'mongoose';
import ConversationModel from '../models/Conversation';
import MessageModel from '../models/Messages';
import ScanModel from '../models/Scan';
import QRCodeModel from '../models/QrCode';
import UserModel from '../models/User';
import GuestUserModel from '../models/GuestUser';

function addScanIdToSet(set: Set<string>, id: unknown) {
  if (id == null) return;
  const s = String(id);
  if (s && mongoose.Types.ObjectId.isValid(s)) {
    set.add(s);
  }
}

/** ObjectId from `conversation.scan_id` whether it is an id or a lean-populated Scan subdoc. */
function rawScanIdFromConversationScanField(raw: unknown): unknown {
  if (raw == null) return null;
  if (raw instanceof mongoose.Types.ObjectId) return raw;
  if (typeof raw === 'object' && '_id' in (raw as object)) {
    return (raw as { _id: unknown })._id;
  }
  return raw;
}

function isLeanPopulatedScanDoc(raw: unknown): boolean {
  return (
    raw != null &&
    typeof raw === 'object' &&
    !(raw instanceof mongoose.Types.ObjectId) &&
    'qrcode_id' in (raw as object)
  );
}

/** Prefer lean-populated conversation scan (from `.withScanPopulate()`), else scansMap, else last message scan. */
function resolvePopulatedScan(
  scansMap: Record<string, unknown>,
  conversation: Record<string, unknown>,
  lastMessage: { scan_id?: unknown } | null
) {
  const convScan = conversation.scan_id;
  if (isLeanPopulatedScanDoc(convScan)) {
    return convScan;
  }
  const convScanId = rawScanIdFromConversationScanField(convScan);
  if (convScanId != null) {
    const key = String(convScanId);
    const hit = scansMap[key];
    if (hit) return hit;
  }
  if (lastMessage?.scan_id != null) {
    const key = String(lastMessage.scan_id);
    const hit = scansMap[key];
    if (hit) return hit;
  }
  return null;
}

// ================ GET CONVERSATIONS DETAILS ========================
export const getConversationsWithDetails = async (myId: string) => {
  try {
    // Step 1: Get conversations for the user
    const conversations = (await (
      ConversationModel.find({
        participants: new mongoose.Types.ObjectId(myId),
      }).sort({ updatedAt: -1 }) as any
    )
      .withScanPopulate()
      .lean()) as Record<string, unknown>[];

    // Step 2: Process each conversation
    const conversationsWithDetails = await Promise.all(
      conversations.map(async (conversation: Record<string, unknown>) => {
        // Get last message
        let lastMessage: { scan_id?: unknown } | null = null;
        if (conversation.last_message) {
          lastMessage = (await MessageModel.findById(
            conversation.last_message
          ).lean()) as { scan_id?: unknown } | null;
        }

        const convScan = conversation.scan_id as unknown;
        let scanDetails: Record<string, unknown> | null = null;
        if (isLeanPopulatedScanDoc(convScan)) {
          scanDetails = convScan as Record<string, unknown>;
        } else {
          const scanIdToLoad =
            rawScanIdFromConversationScanField(convScan) ??
            lastMessage?.scan_id ??
            null;
          if (scanIdToLoad) {
            const scan = (await ScanModel.findById(scanIdToLoad).lean().populate({
              path: 'qrcode_id',
              select: '-pinHash -pin',
              model: QRCodeModel,
            })) as Record<string, unknown> | null;

            if (scan) {
              scanDetails = scan;
            }
          }
        }
        // Get participants details
        const participantsDetails = await getParticipantsDetails(
          conversation.participants as mongoose.Types.ObjectId[]
        );

        // Construct the conversation object
        return {
          _id: conversation._id,
          participants: participantsDetails,
          last_message: lastMessage,
          scan_id: scanDetails,
          updatedAt: conversation.updatedAt,
          createdAt: conversation.createdAt,
          // Include any other fields you need
        };
      })
    );

    return conversationsWithDetails;
  } catch (error) {
    console.error('Error fetching conversations:', error);
    throw error;
  }
};

// ================= GET PARTICIPANTS DETAILS =================
export async function getParticipantsDetails(
  participantIds: mongoose.Types.ObjectId[]
) {
  try {
    const participantsDetails = await Promise.all(
      participantIds.map(async (participantId: mongoose.Types.ObjectId) => {
        // Try to find in users collection first
        const user = (await UserModel.findById(participantId)
          .select('first_name last_name email phone_number profile_picture role')
          .lean()) as any;

        if (user) {
          return {
            _id: user._id,
            first_name: user.first_name,
            last_name: user.last_name,
            email: user.email,
            phone_number: user.phone_number,
            profile_picture: user.profile_picture,
            role: user.role,
            type: 'user',
          };
        }

        // If not found in users, try guest_users
        const guest = (await GuestUserModel.findById(participantId)
          .select('name guest_token device_type')
          .lean()) as any;

        if (guest) {
          return {
            _id: guest._id,
            name: guest.name,
            guest_token: guest.guest_token,
            device_type: guest.device_type,
            type: 'guest',
          };
        }

        // If not found in either collection
        return {
          _id: participantId,
          type: 'unknown',
        };
      })
    );

    return participantsDetails;
  } catch (error) {
    console.error('Error fetching participants details:', error);
    throw error;
  }
}

// ================== GET MY CONVERSATION ==============
export async function getMyConversations(myId: any) {
  try {
    const conversations = await getConversationsWithDetails(myId);
    return conversations;
  } catch (error) {
    console.error('Error in getMyConversations:', error);
    throw error;
  }
}

// Alternative version with optimized queries (batched)
export async function getConversationsOptimized(myId: any) {
  try {
    // Step 1: Get conversations
    const conversations = (await (
      ConversationModel.find({
        participants: new mongoose.Types.ObjectId(myId),
      }).sort({ updatedAt: -1 }) as any
    )
      .withScanPopulate()
      .lean()) as Record<string, unknown>[];

    // Collect all IDs for batch queries
    const allMessageIds = conversations
      .map((c: Record<string, unknown>) => c.last_message)
      .filter(id => id);
    const allParticipantIds = [
      ...new Set(
        conversations.flatMap(
          (c: Record<string, unknown>) => c.participants as mongoose.Types.ObjectId[]
        )
      ),
    ];

    // Step 2: Batch fetch all messages
    const messagesMap: { [key: string]: any } = {};
    if (allMessageIds.length > 0) {
      const messages = await MessageModel.find({
        _id: { $in: allMessageIds },
      }).lean();

      messages.forEach(msg => {
        // @ts-ignore
        messagesMap[msg._id.toString()] = msg;
      });
    }

    const scanIdSet = new Set<string>();
    conversations.forEach((c: Record<string, unknown>) =>
      addScanIdToSet(scanIdSet, rawScanIdFromConversationScanField(c.scan_id))
    );
    conversations.forEach((c: Record<string, unknown>) => {
      if (!c.last_message) return;
      const lm = messagesMap[String(c.last_message)];
      addScanIdToSet(scanIdSet, lm?.scan_id);
    });
    const allScanIds = [...scanIdSet];

    // Step 3: Batch fetch all scans with QR codes
    const scansMap: { [key: string]: any } = {};
    if (allScanIds.length > 0) {
      const scans = (await ScanModel.find({
        _id: { $in: allScanIds },
      })
        .populate({
          path: 'qrcode_id',
          select: '-pinHash -pin',
          model: QRCodeModel,
        })
        .lean()) as any[];

      scans.forEach(scan => {
        // @ts-ignore
        scansMap[scan._id.toString()] = scan;
      });
    }
    // Step 4: Batch fetch all participants
    const participantsMap = await getParticipantsMap(allParticipantIds);

    // Step 5: Construct response
    const conversationsWithDetails = conversations.map(
      (conversation: Record<string, unknown>) => {
        const lastMessage: { scan_id?: unknown } | null = conversation.last_message
          ? ((messagesMap[String(conversation.last_message)] as
              | { scan_id?: unknown }
              | undefined) ?? null)
          : null;

        const scanDetails = resolvePopulatedScan(scansMap, conversation, lastMessage);

        const participantsDetails = (
          conversation.participants as mongoose.Types.ObjectId[]
        ).map((pid: mongoose.Types.ObjectId) => {
          const pidStr = pid.toString();
          // @ts-ignore
          return (
            participantsMap[pidStr] || {
              _id: pid,
              type: 'unknown',
            }
          );
        });

        return {
          ...conversation,
          last_message: lastMessage,
          scan_id: scanDetails,
          participants: participantsDetails,
        };
      }
    );
    return conversationsWithDetails;
  } catch (error) {
    console.error('Error in getConversationsOptimized:', error);
    throw error;
  }
}

export async function getParticipantsMap(participantIds: any) {
  try {
    const participantsMap: Record<string, any> = {};

    // Batch fetch users
    const users = (await UserModel.find({
      _id: { $in: participantIds },
    })
      .select('first_name last_name email phone_number profile_picture role')
      .lean()) as any[];

    users.forEach(user => {
      // @ts-ignore
      participantsMap[user._id.toString()] = {
        _id: user._id,
        first_name: user.first_name,
        last_name: user.last_name,
        email: user.email,
        phone_number: user.phone_number,
        profile_picture: user.profile_picture,
        role: user.role,
        type: 'user',
      };
    });

    // Find which participants are still missing (not found in users)
    const foundUserIds = users.map(u => u._id.toString());
    const remainingIds = participantIds.filter(
      // @ts-ignore
      id => !foundUserIds.includes(id.toString())
    );

    // Batch fetch guests for remaining IDs
    if (remainingIds.length > 0) {
      const guests = await GuestUserModel.find({
        _id: { $in: remainingIds },
      })
        .select('name guest_token device_type')
        .lean();

      guests.forEach(guest => {
        // @ts-ignore
        participantsMap[guest._id.toString()] = {
          _id: guest._id,
          name: guest.name,
          guest_token: guest.guest_token,
          device_type: guest.device_type,
          type: 'guest',
        };
      });
    }

    return participantsMap;
  } catch (error) {
    console.error('Error in getParticipantsMap:', error);
    throw error;
  }
}
