import type { TenantEmotion } from '../api';

export function filterEmotionsByEventType(
  emotions: TenantEmotion[],
  eventTypeId: number | null,
): TenantEmotion[] {
  if (!Array.isArray(emotions) || emotions.length === 0) {
    return [];
  }

  const filtered = emotions.filter((emotion) => {
    if (!emotion.is_active) {
      return false;
    }
    if (!eventTypeId) {
      return true;
    }
    if (!Array.isArray(emotion.event_types) || emotion.event_types.length === 0) {
      return true;
    }
    return emotion.event_types.some((type) => type?.id === eventTypeId);
  });

  return filtered.sort((a, b) => {
    const left = typeof a.sort_order === 'number' ? a.sort_order : Number.MAX_SAFE_INTEGER;
    const right = typeof b.sort_order === 'number' ? b.sort_order : Number.MAX_SAFE_INTEGER;
    return left - right;
  });
}
