//
//  LoadRemoteLocationsUseCase.swift
//  Locations
//
//  Created by Javier Cicchelli on 12/04/2023.
//  Copyright © 2023 Röck+Cöde. All rights reserved.
//

import CoreData
import Dependency
import Persistence
import Remote

struct LoadRemoteLocationsUseCase {
    
    // MARK: Properties
    
    private let persistence: PersistenceService
    private let remoteService: RemoteService
    
    // MARK: Initialisers
    
    init(
        persistence: PersistenceService,
        remoteService: RemoteService
    ) {
        self.persistence = persistence
        self.remoteService = remoteService
    }
    
    func callAsFunction() async throws {
        let context = persistence.makeTaskContext()
        let fetchRequest = NSFetchRequest<Persistence.Location>.allLocations()
        
        try await context.perform {
            let localLocations = try context.fetch(fetchRequest)
            
            localLocations
                .filter { $0.source == .remote }
                .forEach(context.delete)
        }

        let remoteLocations = try await remoteService.getLocations()

        _ = remoteLocations
            .map {
                let entity = Persistence.Location(context: context)
                
                entity.createdAt = .now
                entity.name = $0.name
                entity.latitude = $0.latitude
                entity.longitude = $0.longitude
                entity.source = .remote
                
                return entity
            }
            
        persistence.save(context: context)
    }

}

// MARK: - LoadRemoteLocationsUseCase+Initialisers

extension LoadRemoteLocationsUseCase {
    init() {
        @Dependency(\.persistence) var persistence
        @Dependency(\.remote) var remote
        
        self.init(
            persistence: persistence,
            remoteService: remote
        )
    }
}
