//
//  DeleteStatusService.swift
//  Tusker
//
//  Created by Shadowfacts on 1/17/23.
//  Copyright © 2023 Shadowfacts. All rights reserved.
//

import UIKit
import Pachyderm

@MainActor
class DeleteStatusService {
    let status: StatusMO
    let mastodonController: MastodonController
    let presenter: any TuskerNavigationDelegate
    
    init(status: StatusMO, mastodonController: MastodonController, presenter: any TuskerNavigationDelegate) {
        self.status = status
        self.mastodonController = mastodonController
        self.presenter = presenter
    }
    
    func run() async {
        do {
            let req = Status.delete(status.id)
            let _ = try await mastodonController.run(req)
            
            // we deliberately don't remove the status from the cache because there are almost certainly places where it'll still be fetched again
            
            var reblogIDs = [String]()
            let reblogsReq = StatusMO.fetchRequest()
            reblogsReq.predicate = NSPredicate(format: "reblog = %@", status)
            if let reblogs = try? mastodonController.persistentContainer.viewContext.fetch(reblogsReq) {
                reblogIDs = reblogs.map(\.id)
            }
            
            NotificationCenter.default.post(name: .statusDeleted, object: mastodonController, userInfo: [
                "statusIDs": [status.id] + reblogIDs,
            ])
        } catch {
            let message: String
            if let error = error as? Client.Error {
                message = error.localizedDescription
            } else {
                message = error.localizedDescription
            }
            let alert = UIAlertController(title: "Error Deleting Post", message: message, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
            alert.addAction(UIAlertAction(title: "Retry", style: .default, handler: { _ in
                Task {
                    await self.run()
                }
            }))
            presenter.present(alert, animated: true)
        }
    }
}

extension Foundation.Notification.Name {
    static let statusDeleted = Foundation.Notification.Name("statusDeleted")
}
