import { MatrixEvent, Room } from 'matrix-js-sdk';

/** The Matrix state event type for call membership (MSC3401) */
export const CALL_MEMBER_EVENT_TYPE = 'org.matrix.msc3401.call.member';

/** Represents an active call member in a room */
export interface CallMember {
  userId: string;
  deviceId: string;
  sessionId: string;
  expiresTs: number;
}

/**
 * Extracts active call members from a room's state events
 */
export function getActiveCallMembers(room: Room): CallMember[] {
  const members: CallMember[] = [];
  const now = Date.now();

  try {
    const stateEvents = room.currentState.getStateEvents(CALL_MEMBER_EVENT_TYPE);

    stateEvents.forEach((event) => {
      const content = event.getContent();
      const userId = event.getStateKey();

      if (!userId || !content['m.calls']) return;

      const calls = content['m.calls'];
      if (!Array.isArray(calls)) return;

      calls.forEach((call) => {
        const devices = call['m.devices'];
        if (!Array.isArray(devices)) return;

        devices.forEach((device) => {
          const expiresTs = device.expires_ts || 0;

          if (expiresTs > now) {
            members.push({
              userId,
              deviceId: device.device_id,
              sessionId: device.session_id,
              expiresTs,
            });
          }
        });
      });
    });
  } catch {
    // Ignore malformed call member events
  }

  return members;
}

export function isCallMemberEvent(event: MatrixEvent): boolean {
  return event.getType() === CALL_MEMBER_EVENT_TYPE;
}
