import {
  loadPulseConfig,
  updatePulseConfig,
  type PulseConfig,
} from 'priority-forge-hub';
import { TeamPulseConfig, DEFAULT_TEAM_PULSE_CONFIG } from './types';

function pulseToTeamPulse(pulse: PulseConfig): TeamPulseConfig {
  return {
    enabled: pulse.emit,
    userId: pulse.userId,
    pushImmediately: pulse.pushImmediately,
    privacyRules: pulse.privacyRules,
  };
}

function teamPulseToPulsePatch(updates: Partial<TeamPulseConfig>): Partial<PulseConfig> {
  const patch: Partial<PulseConfig> = {};
  if (updates.enabled !== undefined) patch.emit = updates.enabled;
  if (updates.userId !== undefined) patch.userId = updates.userId;
  if (updates.pushImmediately !== undefined) {
    patch.pushImmediately = updates.pushImmediately as PulseConfig['pushImmediately'];
  }
  if (updates.privacyRules !== undefined) {
    patch.privacyRules = updates.privacyRules;
  }
  return patch;
}

export function loadTeamPulseConfig(): TeamPulseConfig {
  try {
    return pulseToTeamPulse(loadPulseConfig());
  } catch {
    return { ...DEFAULT_TEAM_PULSE_CONFIG };
  }
}

export function saveTeamPulseConfig(config: TeamPulseConfig): void {
  updatePulseConfig({
    emit: config.enabled,
    userId: config.userId,
    pushImmediately: config.pushImmediately,
    privacyRules: config.privacyRules,
  });
}

export function updateTeamPulseConfig(
  updates: Partial<TeamPulseConfig>,
): TeamPulseConfig {
  const next = updatePulseConfig(teamPulseToPulsePatch(updates));
  return pulseToTeamPulse(next);
}
