import SwiftData
import SwiftUI

@Model final class Parent {
  init() {
    child = Child()
  }
  @Transient let uuid =  UUID()
  @Relationship(deleteRule: .cascade, inverse: \Child.parent) var child: Child?
}

@Model final class Child {
  init(){}
  @Transient let uuid =  UUID()
  var parent: Parent?
}

struct ParentChildView: View {
  @Environment(\.modelContext) var modelContext
  @Query var parents: [Parent]
  var body: some View {
    VStack {
      Text("Test")
      Spacer()
      ForEach(parents) { parent in
        Text("Parent === itself: \(String(describing: parent === parent))")
        Text("Parent.uuid == itself \(String(describing: parent.uuid == parent.uuid))")
        Text("Child === itself when retrieved twice: \(String(describing: parent.child === parent.child))")
        Text("Child.uuid == itself when retrieved twice: \(String(describing: (parent.child!.uuid == parent.child!.uuid)))")
        let child = parent.child
        Text("Child.uuid == itself when retained: \(String(describing: (parent.child!.uuid == parent.child!.uuid)))")
      }
    }
    .onAppear {
      modelContext.insert(Parent())
      try! modelContext.save()
    }
  }
}

#Preview {
  ParentChildView().modelContainer(for: [Parent.self, Child.self], inMemory: true)
}

// Parent === itself: true
// Parent.uuid == itself true
// Child === itself when retrieved twice: true
// Child.uuid == itself when retrieved twice: false
// Child.uuid == itself when retained: true