import Foundation
import RealmSwift

struct Database {
    let db: Realm

    init() {
        do {
            var dbConfig = Realm.Configuration.init()
            dbConfig.fileURL = Database.storeURL
            dbConfig.schemaVersion = Database.actualSchemaVersion
            dbConfig.migrationBlock = Database.migrations
            dbConfig.encryptionKey = Database.encryptionKey
            db = try Realm(configuration: dbConfig)
        } catch {
            fatalError("Realm DB initialization")
        }

        #if DEBUG
            print("DB path: \(Database.storeURL?.description ?? "???")")
            print("DB key: \(Database.encryptionKey)")
        #endif
    }
}

extension Database {
    static var storeURL: URL? {
        guard let docDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return nil }
        return docDir.appendingPathComponent("main.realm")
    }
}
