//
//  NotificationService.swift
//  TheNoiseClock
//
//  Created by Matt Bruce on 9/7/25.
//

import Foundation
import UserNotifications
import Observation
import Bedrock

/// Service for managing system notifications
@Observable
class NotificationService {
    
    // MARK: - Properties
    private(set) var isAuthorized = false
    
    // MARK: - Initialization
    init() {
        checkAuthorizationStatus()
    }
    
    // MARK: - Public Interface
    func requestPermissions() async -> Bool {
        do {
            let granted = try await UNUserNotificationCenter.current().requestAuthorization(
                options: [.alert, .sound, .badge]
            )
            isAuthorized = granted
            return granted
        } catch {
            Design.debugLog("[general] Error requesting notification permissions: \(error)")
            isAuthorized = false
            return false
        }
    }
    
    func checkAuthorizationStatus() {
        UNUserNotificationCenter.current().getNotificationSettings { settings in
            DispatchQueue.main.async {
                self.isAuthorized = settings.authorizationStatus == .authorized
            }
        }
    }
    
    /// Schedule a single alarm notification
    @discardableResult
    func scheduleAlarmNotification(
        id: String,
        title: String,
        body: String,
        soundName: String,
        date: Date
    ) async -> Bool {
        guard isAuthorized else {
            Design.debugLog("[settings] Notifications not authorized")
            return false
        }
        
        let content = NotificationUtils.createAlarmContent(
            title: title,
            body: body,
            soundName: soundName
        )
        let trigger = NotificationUtils.createCalendarTrigger(for: date)
        
        return await NotificationUtils.scheduleNotification(
            identifier: id,
            content: content,
            trigger: trigger
        )
    }
    
    
    /// Cancel a single notification
    func cancelNotification(id: String) {
        NotificationUtils.removeNotification(identifier: id)
    }
    
    /// Cancel all notifications
    func cancelAllNotifications() {
        NotificationUtils.removeAllNotifications()
    }
    
}
