//
//  BackgroundManager.swift
//  Tusker
//
//  Created by Shadowfacts on 5/15/23.
//  Copyright © 2023 Shadowfacts. All rights reserved.
//

import Foundation
import BackgroundTasks
import OSLog
import ComposeUI

private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "BackgroundManager")

struct BackgroundManager {
    static let shared = BackgroundManager()
    
    private init() {}
    
    static let cleanupAttachmentsIdentifier = "\(Bundle.main.bundleIdentifier!).cleanup-attachments"
    
    func scheduleTasks() {
        BGTaskScheduler.shared.getPendingTaskRequests { requests in
            if !requests.contains(where: { $0.identifier == Self.cleanupAttachmentsIdentifier }) {
                let request = BGProcessingTaskRequest(identifier: Self.cleanupAttachmentsIdentifier)
                do {
                    try BGTaskScheduler.shared.submit(request)
                } catch {
                    logger.error("Failed to schedule cleanup attachments: \(String(describing: error), privacy: .public)")
                }
            }
        }
    }
    
    func registerHandlers() {
        BGTaskScheduler.shared.register(forTaskWithIdentifier: Self.cleanupAttachmentsIdentifier, using: nil, launchHandler: handleCleanupAttachments(_:))
    }
    
    private func handleCleanupAttachments(_ task: BGTask) {
        DraftsPersistentContainer.shared.removeOrphanedAttachments() {
            task.setTaskCompleted(success: true)
        }
    }
}
