import Foundation
import React

@objc(LayersDeviceInfo)
class LayersDeviceInfo: NSObject {

  @objc
  func getModelIdentifier(_ resolve: @escaping (Any?) -> Void, rejecter reject: @escaping (String?, String?, Error?) -> Void) {
    var systemInfo = utsname()
    uname(&systemInfo)
    let model = withUnsafePointer(to: &systemInfo.machine) {
      $0.withMemoryRebound(to: CChar.self, capacity: 1) {
        String(validatingUTF8: $0) ?? "Unknown"
      }
    }
    resolve(model)
  }

  @objc
  func getAppVersion(_ resolve: @escaping (Any?) -> Void, rejecter reject: @escaping (String?, String?, Error?) -> Void) {
    let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
    resolve(version)
  }

  /// Returns the approximate first install time (milliseconds since epoch) by
  /// reading the creation date of the app's Documents directory. This is a
  /// reliable proxy on iOS — the directory is created when the app is first
  /// installed and survives app updates (but not uninstall/reinstall).
  /// Used for install event gating to suppress false `is_first_launch` events
  /// when the SDK is added to an existing app.
  @objc
  func getFirstInstallTime(_ resolve: @escaping (Any?) -> Void, rejecter reject: @escaping (String?, String?, Error?) -> Void) {
    guard let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
      resolve(nil)
      return
    }
    do {
      let attrs = try FileManager.default.attributesOfItem(atPath: documentsURL.path)
      if let creationDate = attrs[.creationDate] as? Date {
        resolve(creationDate.timeIntervalSince1970 * 1000.0)
      } else {
        resolve(nil)
      }
    } catch {
      resolve(nil)
    }
  }

  @objc
  static func requiresMainQueueSetup() -> Bool {
    return false
  }
}
