import Foundation
import ServiceManagement

/// Registers the app to start at login, via macOS's own login-items service.
///
/// No helper tool and no scripting: `SMAppService.mainApp` registers the bundle itself,
/// and the user can always override it in System Settings › General › Login Items.
enum LoginItem {
    static var isEnabled: Bool {
        SMAppService.mainApp.status == .enabled
    }

    /// Returns nil on success, or a human-readable reason it didn't work.
    static func set(_ enabled: Bool) -> String? {
        do {
            if enabled {
                // Already registered is not an error worth surfacing.
                guard SMAppService.mainApp.status != .enabled else { return nil }
                try SMAppService.mainApp.register()
            } else {
                guard SMAppService.mainApp.status == .enabled else { return nil }
                try SMAppService.mainApp.unregister()
            }
            return nil
        } catch {
            // The usual cause is running the bare binary rather than the .app bundle.
            return "Couldn't change the login item: \(error.localizedDescription). "
                + "Add it by hand in System Settings › General › Login Items."
        }
    }
}
