#!/usr/bin/env bash
set -euo pipefail

LABEL="com.online-clinic.startup"
LEGACY_LABEL="com.online-clinic.api"
SERVICE_NAME="online-clinic-startup.service"
LEGACY_SERVICE_NAME="online-clinic-api.service"

case "$(uname -s)" in
  Darwin)
    for old_label in "$LEGACY_LABEL" "$LABEL"; do
      launchctl bootout "gui/$(id -u)/${old_label}" 2>/dev/null || true
      if [[ -f "$HOME/Library/LaunchAgents/${old_label}.plist" ]]; then
        rm -f "$HOME/Library/LaunchAgents/${old_label}.plist"
        echo "Removed macOS LaunchAgent: ${old_label}"
      fi
    done
    ;;
  Linux)
    for old_service in "$LEGACY_SERVICE_NAME" "$SERVICE_NAME"; do
      systemctl --user disable "$old_service" 2>/dev/null || true
      systemctl --user stop "$old_service" 2>/dev/null || true
      if [[ -f "${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user/$old_service" ]]; then
        rm -f "${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user/$old_service"
        echo "Removed systemd user service: $old_service"
      fi
    done
    systemctl --user daemon-reload
    ;;
  *)
    echo "Nothing to remove on this OS."
    exit 1
    ;;
esac
