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

import Foundation
import UserAccounts

@MainActor
class LogoutService {
    let accountInfo: UserAccountInfo
    private let mastodonController: MastodonController
    
    init(accountInfo: UserAccountInfo) {
        self.accountInfo = accountInfo
        self.mastodonController = MastodonController.getForAccount(accountInfo)
    }
    
    func run() {
        Task.detached {
            try? await self.mastodonController.client.revokeAccessToken()
        }
        MastodonController.removeForAccount(accountInfo)
        UserAccountsManager.shared.removeAccount(accountInfo)
        let psc = mastodonController.persistentContainer.persistentStoreCoordinator
        for store in psc.persistentStores {
            guard let url = store.url else {
                continue
            }
            try? psc.destroyPersistentStore(at: url, type: .sqlite)
        }
    }
}
