import mongoose from 'mongoose';
import QrCodeModel from '../models/QrCode';
import ScanModel from '../models/Scan';

type ScanIdDoc = { _id: mongoose.Types.ObjectId } | null;

export type ResolveConversationScanOptions = {
  /**
   * Guest / anonymous sockets only. When true, `qrcode_id` is honored:
   * scan lookups are scoped to that QR, and a direct Scan id must belong to it.
   */
  forAnonymousUser?: boolean;
  /** QR code document _id — used only together with `forAnonymousUser`. */
  qrcode_id?: string;
};

/**
 * Of the two chat participants, return the one that is not the QR owner (the visitor / scanner).
 */
function visitorIdExcludingOwner(
  ownerUserId: string,
  myId: string,
  otherUserId: string
): string | null {
  const o = String(ownerUserId);
  const a = String(myId);
  const b = String(otherUserId);
  if (a === o && b !== o) return b;
  if (b === o && a !== o) return a;
  return null;
}

/**
 * Socket/chat clients sometimes send a QR code id as `scan_id` instead of the Scan
 * document _id. Conversations are keyed by Scan._id so each scan session stays separate.
 * - If `scanIdFromClient` is a real Scan _id, use it (for anonymous users, optional
 *   `qrcode_id` in options must match that scan's `qrcode_id` when provided).
 * - Else if it is a QR code id (or anonymous-only `qrcode_id` is passed without a scan id),
 *   use the latest Scan for that QR where the visitor (participant who is not the QR
 *   `created_by` owner) is `scanned_by`.
 * - If the visitor cannot be determined, fall back to the legacy query (either
 *   participant may appear as scanned_by).
 */
export async function resolveConversationScanObjectId(
  scanIdFromClient: string | undefined,
  myId: string,
  otherUserId: string,
  resolveOpts?: ResolveConversationScanOptions
): Promise<mongoose.Types.ObjectId | null> {
  const anon = resolveOpts?.forAnonymousUser === true;
  const extraQrRaw = resolveOpts?.qrcode_id?.trim();
  const extraQrOid =
    anon && extraQrRaw && mongoose.Types.ObjectId.isValid(extraQrRaw)
      ? new mongoose.Types.ObjectId(extraQrRaw)
      : null;

  const raw = scanIdFromClient?.trim();
  const hasRaw = !!(raw && mongoose.Types.ObjectId.isValid(raw));
  const candidate = hasRaw ? new mongoose.Types.ObjectId(raw) : null;

  if (!candidate && !extraQrOid) {
    return null;
  }

  if (candidate) {
    const asScan = (await ScanModel.findById(candidate)
      .select('_id qrcode_id')
      .lean()
      .exec()) as {
      _id?: mongoose.Types.ObjectId;
      qrcode_id?: mongoose.Types.ObjectId;
    } | null;

    if (asScan?._id) {
      if (anon && extraQrOid) {
        const sid = asScan.qrcode_id;
        if (!sid || String(sid) !== String(extraQrOid)) {
          return null;
        }
      }
      return new mongoose.Types.ObjectId(String(asScan._id));
    }
  }

  const qrcodeFilterOid = anon && extraQrOid ? extraQrOid : candidate;
  if (!qrcodeFilterOid) {
    return null;
  }

  const qr = (await QrCodeModel.findById(qrcodeFilterOid)
    .select('created_by')
    .lean()
    .exec()) as { created_by?: mongoose.Types.ObjectId } | null;

  const ownerStr = qr?.created_by != null ? String(qr.created_by) : '';
  const visitorStr = ownerStr
    ? visitorIdExcludingOwner(ownerStr, myId, otherUserId)
    : null;

  if (visitorStr && mongoose.Types.ObjectId.isValid(visitorStr)) {
    const visitorOid = new mongoose.Types.ObjectId(visitorStr);
    const visitorLatest = (await ScanModel.findOne({
      qrcode_id: qrcodeFilterOid,
      scanned_by: visitorOid,
    })
      .sort({ createdAt: -1 })
      .select('_id')
      .lean()
      .exec()) as ScanIdDoc;

    if (visitorLatest?._id) {
      return new mongoose.Types.ObjectId(String(visitorLatest._id));
    }
  }

  const latest = (await ScanModel.findOne({
    qrcode_id: qrcodeFilterOid,
    $or: [
      { scanned_by: new mongoose.Types.ObjectId(myId) },
      { scanned_by: new mongoose.Types.ObjectId(otherUserId) },
    ],
  })
    .sort({ createdAt: -1 })
    .select('_id')
    .lean()
    .exec()) as ScanIdDoc;

  if (!latest?._id) {
    return null;
  }

  return new mongoose.Types.ObjectId(String(latest._id));
}
