type StreamSessionLike = {
  id: string;
  ownerUserId: string;
  cameraDeviceId: string;
  requesterDeviceId: string;
  status: string;
  reason: string;
  metadata: Record<string, unknown> | null;
  startedAt: Date | null;
  endedAt: Date | null;
  createdAt: Date;
  updatedAt: Date;
};

type StreamEndedPayloadInput = {
  streamSessionId: string;
  cameraDeviceId: string;
  requesterDeviceId: string;
  endedAt: Date;
  reason: 'completed' | 'cancelled' | 'failed';
};

export const isStreamParticipant = (session: Pick<StreamSessionLike, 'cameraDeviceId' | 'requesterDeviceId'>, deviceId: string): boolean =>
  session.cameraDeviceId === deviceId || session.requesterDeviceId === deviceId;

export const canRelayWebrtcSignal = (
  session: Pick<StreamSessionLike, 'cameraDeviceId' | 'requesterDeviceId'>,
  fromDeviceId: string,
  toDeviceId: string,
): boolean => {
  if (fromDeviceId === toDeviceId) {
    return false;
  }

  return isStreamParticipant(session, fromDeviceId) && isStreamParticipant(session, toDeviceId);
};

export const createStreamRequestedPayload = (
  session: Pick<StreamSessionLike, 'id' | 'cameraDeviceId' | 'requesterDeviceId' | 'status' | 'reason'>,
) => ({
  streamSessionId: session.id,
  cameraDeviceId: session.cameraDeviceId,
  requesterDeviceId: session.requesterDeviceId,
  status: session.status,
  reason: session.reason,
});

export const createStreamStartedPayload = (
  session: Pick<StreamSessionLike, 'id' | 'cameraDeviceId' | 'requesterDeviceId' | 'status' | 'startedAt'>,
) => ({
  streamSessionId: session.id,
  cameraDeviceId: session.cameraDeviceId,
  requesterDeviceId: session.requesterDeviceId,
  status: session.status,
  startedAt: session.startedAt,
  transport: 'webrtc',
});

export const createStreamEndedPayload = (input: StreamEndedPayloadInput) => ({
  streamSessionId: input.streamSessionId,
  cameraDeviceId: input.cameraDeviceId,
  requesterDeviceId: input.requesterDeviceId,
  status: 'ended',
  endedAt: input.endedAt,
  reason: input.reason,
});

export const toSimpleStreamSessionResponse = (session: StreamSessionLike) => ({
  id: session.id,
  ownerUserId: session.ownerUserId,
  cameraDeviceId: session.cameraDeviceId,
  requesterDeviceId: session.requesterDeviceId,
  status: session.status,
  reason: session.reason,
  metadata: session.metadata,
  startedAt: session.startedAt,
  endedAt: session.endedAt,
  createdAt: session.createdAt,
  updatedAt: session.updatedAt,
});
