import type { RoomSummary } from './types';

export type MessageSoundMode = 'all' | 'mentions_dms' | 'off';

export interface MessageSoundSettings {
  mode: MessageSoundMode;
  sound: string | null;
}

export const DEFAULT_MESSAGE_SOUND: MessageSoundSettings = { mode: 'mentions_dms', sound: null };
export const SOUND_MAX_BYTES = 1024 * 1024;
export const SOUND_THROTTLE_MS = 1500;

export function parseMessageSound(raw: unknown): MessageSoundSettings {
  if (typeof raw !== 'object' || raw === null) return DEFAULT_MESSAGE_SOUND;
  const { mode, sound } = raw as Record<string, unknown>;
  return {
    mode: mode === 'all' || mode === 'mentions_dms' || mode === 'off' ? mode : DEFAULT_MESSAGE_SOUND.mode,
    sound: typeof sound === 'string' && sound.startsWith('mxc://') ? sound : null
  };
}

export function shouldPlaySound(
  mode: MessageSoundMode,
  room: Pick<RoomSummary, 'direct'>,
  arrival: { mention: boolean },
  lastPlayedAt: number,
  now: number
): boolean {
  if (mode === 'off' || now - lastPlayedAt < SOUND_THROTTLE_MS) return false;
  return mode === 'all' || arrival.mention || room.direct;
}
