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

import Foundation
import Pachyderm

@MainActor
class FetchStatusService {
    let statusID: String
    let mastodonController: MastodonController
    
    init(statusID: String, mastodonController: MastodonController) {
        self.statusID = statusID
        self.mastodonController = mastodonController
    }
    
    func run() async -> Result {
        let response = await mastodonController.runResponse(Client.getStatus(id: statusID))
        switch response {
        case .success(let status, _):
            return .loaded(status)
        case .failure(let error):
            switch error.type {
            case .unexpectedStatus(404), .mastodonError(404, _):
                self.handleStatusNotFound()
                return .notFound
            default:
                return .error(error)
            }
        }
    }
    
    private func handleStatusNotFound() {
        var reblogIDs = [String]()
        if let cached = mastodonController.persistentContainer.status(for: statusID) {
            let reblogsReq = StatusMO.fetchRequest()
            reblogsReq.predicate = NSPredicate(format: "reblog = %@", cached)
            if let reblogs = try? mastodonController.persistentContainer.viewContext.fetch(reblogsReq) {
                reblogIDs = reblogs.map(\.id)
            }
        }
        
        NotificationCenter.default.post(name: .statusDeleted, object: mastodonController, userInfo: [
            "statusIDs": [statusID] + reblogIDs
        ])
    }
    
    enum Result {
        case loaded(Status)
        case notFound
        case error(Client.Error)
    }
}
