1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
use crate::{bindings::*, utils::*, FFIResult, GraphError};
use dsnp_graph_config::{errors::DsnpGraphError, Config as RustConfig, ConnectionType, SchemaId};
use dsnp_graph_core::{
	api::{
		api::{GraphAPI, GraphState},
		api_types::ActionOptions,
	},
	dsnp::dsnp_types::DsnpUserId,
	util::transactional_hashmap::Transactional,
};
use std::{
	ffi::{c_char, CString},
	mem::ManuallyDrop,
	panic,
	sync::Mutex,
};

#[no_mangle]
pub extern "C" fn print_hello_graph() {
	println!("Hello, Graph!");
}

// Collection of GraphStates
#[allow(clippy::vec_box)]
static GRAPH_STATES: Mutex<Vec<Box<GraphState>>> = Mutex::new(Vec::new());

/// Get the graph config for the given environment
/// # Safety
/// This function is unsafe because it dereferences a raw pointer
/// # Arguments
/// * `environment` - a pointer to an environment
/// # Returns
/// * `Config` - the graph config
/// # Errors
/// * `GraphError` - if the graph config cannot be retrieved
#[no_mangle]
pub unsafe extern "C" fn get_graph_config(
	environment: *const Environment,
) -> FFIResult<Config, GraphError> {
	let result = panic::catch_unwind(|| {
		let env = &*environment;
		let config_for_ffi = get_config_for_ffi(env);
		FFIResult::new(config_for_ffi)
	});

	result.unwrap_or_else(|error| {
		FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::Unknown(anyhow::anyhow!(
			"Failed to get graph config: {:?}",
			error
		))))
	})
}

// Get the schema ID corresponding to the specified connection type using
// the given Config.
/// # Safety
/// This function is unsafe because it dereferences a raw pointer
/// # Arguments
/// * `config` - a pointer to a Config struct
/// # Returns
/// * `SchemaId` - the schema id
/// # Errors
/// * `GraphError` - if the given connection type does not map to a schema in the config
#[no_mangle]
pub unsafe extern "C" fn get_schema_id_from_config(
	connection_type: *const ConnectionType,
	config: *const Config,
) -> FFIResult<SchemaId, GraphError> {
	let cfg = &*config;
	let rust_config: RustConfig = config_from_ffi(cfg);
	let schema_id: Option<SchemaId> =
		rust_config.get_schema_id_from_connection_type(*connection_type);
	match schema_id {
		Some(id) => FFIResult::new(id),
		None => FFIResult::new_mut_error(GraphError::from_error(
			DsnpGraphError::UnsupportedConnectionTypeForConfig(*connection_type),
		)),
	}
}

/// Initialize a graph state with the given environment
/// # Safety
/// This function is unsafe because it dereferences a raw pointer
/// # Arguments
/// * `environment` - a pointer to an environment
/// # Returns
/// * `GraphState` - the pointer to the graph state
/// # Errors
/// * `GraphError` - if the graph state cannot be initialized
#[no_mangle]
pub unsafe extern "C" fn initialize_graph_state(
	environment: *const Environment,
) -> FFIResult<GraphState, GraphError> {
	let result = panic::catch_unwind(|| {
		let environment = &*environment;
		let rust_environment = environment_from_ffi(environment);
		let graph_state = Box::new(GraphState::new(rust_environment));
		let graph_state_ptr = Box::into_raw(graph_state);
		let mut graph_states = GRAPH_STATES.lock().unwrap();
		graph_states.push(Box::from_raw(graph_state_ptr));
		FFIResult::new_mut(graph_state_ptr)
	});
	result.unwrap_or_else(|error| {
		FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::Unknown(anyhow::anyhow!(
			"Failed to initialize graph state: {:?}",
			error
		))))
	})
}

/// Get total graph states in GRAPH_STATES collection
/// # Returns
/// * `usize` - the total graph states in GRAPH_STATES collection
/// # Errors
/// * `GraphError` - if the count of graph states cannot be retrieved
#[no_mangle]
pub unsafe extern "C" fn get_graph_states_count() -> FFIResult<usize, GraphError> {
	let result = panic::catch_unwind(|| {
		let graph_states = GRAPH_STATES.lock().unwrap();
		FFIResult::new(graph_states.len())
	});
	result.unwrap_or_else(|error| {
		FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::Unknown(anyhow::anyhow!(
			"Failed to get graph states count: {:?}",
			error
		))))
	})
}

/// Check if a given state contains user graph
/// # Safety
/// This function is unsafe because it dereferences a raw pointer
/// # Arguments
/// * `graph_state` - a pointer to a graph state
/// * `user_id` - a pointer to a user id
/// # Returns
/// * `bool` - true if the user graph exists, false otherwise
/// # Errors
/// * `GraphError` - if state fails to check if user graph exists
#[no_mangle]
pub unsafe extern "C" fn graph_contains_user(
	graph_state: *mut GraphState,
	user_id: *const DsnpUserId,
) -> FFIResult<bool, GraphError> {
	let result = panic::catch_unwind(|| {
		if graph_state.is_null() {
			return FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::FFIError(
				"Graph state is null".to_string(),
			)));
		}
		let graph_state = &mut *graph_state;
		let user_id = &*user_id;
		FFIResult::new(graph_state.contains_user_graph(user_id))
	});
	result.unwrap_or_else(|error| {
		FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::Unknown(anyhow::anyhow!(
			"Failed to check graph state for user: {:?}",
			error
		))))
	})
}

/// Count of users in current graph state
/// # Safety
/// This function is unsafe because it dereferences a raw pointer
/// # Arguments
/// * `graph_state` - a pointer to a graph state
/// # Returns
/// * `usize` - the count of users in the graph state
/// # Errors
/// * `GraphError` - if state fails to get users count
#[no_mangle]
pub unsafe extern "C" fn graph_users_count(
	graph_state: *mut GraphState,
) -> FFIResult<usize, GraphError> {
	let result = panic::catch_unwind(|| {
		if graph_state.is_null() {
			return FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::FFIError(
				"Graph state is null".to_string(),
			)));
		}
		let graph_state = &mut *graph_state;
		FFIResult::new(graph_state.len())
	});
	result.unwrap_or_else(|error| {
		FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::Unknown(anyhow::anyhow!(
			"Failed to get users count from graph: {:?}",
			error
		))))
	})
}

/// Remove user from graph state
/// # Safety
/// This function is unsafe because it dereferences a raw pointer
/// # Arguments
/// * `graph_state` - a pointer to a graph state
/// * `user_id` - a pointer to a user id
/// # Returns
/// * `bool` - true if the user was removed, false otherwise
/// # Errors
/// * `GraphError` - if the graph state fails to remove user
#[no_mangle]
pub unsafe extern "C" fn graph_remove_user(
	graph_state: *mut GraphState,
	user_id: *const DsnpUserId,
) -> FFIResult<bool, GraphError> {
	let result = panic::catch_unwind(|| {
		if graph_state.is_null() {
			return FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::FFIError(
				"Graph state is null".to_string(),
			)));
		}
		let graph_state = &mut *graph_state;
		let user_id = &*user_id;
		graph_state.remove_user_graph(user_id);
		FFIResult::new(true)
	});
	result.unwrap_or_else(|error| {
		FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::Unknown(anyhow::anyhow!(
			"Failed to remove user from graph: {:?}",
			error
		))))
	})
}

/// Import users data to graph state
/// # Safety
/// This function is unsafe because it dereferences a raw pointer
/// # Arguments
/// * `graph_state` - a pointer to a graph state
/// * `payloads` - a pointer to an array of payloads
/// * `payloads_len` - the length of the payloads array
/// # Returns
/// * `bool` - true if the users data was imported, false otherwise
/// # Errors
/// * `GraphError` - if the graph state fails to import users data
#[no_mangle]
pub unsafe extern "C" fn graph_import_users_data(
	graph_state: *mut GraphState,
	payloads: *const ImportBundle,
	payloads_len: usize,
) -> FFIResult<bool, GraphError> {
	let result = panic::catch_unwind(|| {
		if graph_state.is_null() {
			return FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::FFIError(
				"Graph state is null".to_string(),
			)));
		}
		let graph_state = &mut *graph_state;
		let payloads = std::slice::from_raw_parts(payloads, payloads_len);
		let payloads = payloads_from_ffi(&payloads);
		let imported = graph_state.import_users_data(&payloads);
		match imported {
			Ok(_) => FFIResult::new(true),
			Err(error) => FFIResult::new_mut_error(GraphError::from_error(error)),
		}
	});
	result.unwrap_or_else(|error| {
		FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::Unknown(anyhow::anyhow!(
			"Failed to import users data to graph: {:?}",
			error
		))))
	})
}

/// Export updates from graph state
/// # Safety
/// This function is unsafe because it dereferences a raw pointer
/// # Arguments
/// * `graph_state` - a pointer to a graph state
/// # Returns
/// * `GraphUpdates` - the pointer to the graph updates
/// # Errors
/// * `GraphError` - if the graph updates cannot be retrieved
#[no_mangle]
pub unsafe extern "C" fn graph_export_updates(
	graph_state: *mut GraphState,
) -> FFIResult<GraphUpdates, GraphError> {
	let result = panic::catch_unwind(|| {
		if graph_state.is_null() {
			return FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::FFIError(
				"Graph state is null".to_string(),
			)));
		}
		let graph_state = &mut *graph_state;
		match graph_state.export_updates() {
			Ok(updates) => {
				let ffi_updates = updates_to_ffi(updates);
				let updates_len = ffi_updates.len();
				let updates_ptr = ManuallyDrop::new(ffi_updates).as_mut_ptr();
				let graph_updates = GraphUpdates { updates: updates_ptr, updates_len };
				FFIResult::new(graph_updates)
			},
			Err(error) => FFIResult::new_mut_error(GraphError::from_error(error)),
		}
	});
	result.unwrap_or_else(|error| {
		FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::Unknown(anyhow::anyhow!(
			"Failed to export updates from graph: {:?}",
			error
		))))
	})
}

/// Export updates from graph state
/// # Safety
/// This function is unsafe because it dereferences a raw pointer
/// # Arguments
/// * `graph_state` - a pointer to a graph state
/// # Returns
/// * `GraphUpdates` - the pointer to the graph updates
/// # Errors
/// * `GraphError` - if the graph updates cannot be retrieved
#[no_mangle]
pub unsafe extern "C" fn graph_export_user_graph_updates(
	graph_state: *mut GraphState,
	user_id: *const DsnpUserId,
) -> FFIResult<GraphUpdates, GraphError> {
	let result = panic::catch_unwind(|| {
		if graph_state.is_null() {
			return FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::FFIError(
				"Graph state is null".to_string(),
			)));
		}
		let graph_state = &mut *graph_state;
		match graph_state.export_user_graph_updates(&*user_id) {
			Ok(updates) => {
				let ffi_updates = updates_to_ffi(updates);
				let updates_len = ffi_updates.len();
				let updates_ptr = ManuallyDrop::new(ffi_updates).as_mut_ptr();
				let graph_updates = GraphUpdates { updates: updates_ptr, updates_len };
				FFIResult::new(graph_updates)
			},
			Err(error) => FFIResult::new_mut_error(GraphError::from_error(error)),
		}
	});
	result.unwrap_or_else(|error| {
		FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::Unknown(anyhow::anyhow!(
			"Failed to export updates from graph: {:?}",
			error
		))))
	})
}

/// Force recalculate graph updates from graph state
/// # Safety
/// This function is unsafe because it dereferences a raw pointer
/// # Arguments
/// * `graph_state` - a pointer to the graph state
/// * `user_id` - a pointer to a user id
/// # Returns
/// * `GraphUpdates` - the pointer to the graph updates
/// # Errors
/// * `GraphError` - if the graph updates cannot be retrieved
#[no_mangle]
pub unsafe extern "C" fn graph_force_recalculate_updates(
	graph_state: *mut GraphState,
	user_id: *const DsnpUserId,
) -> FFIResult<GraphUpdates, GraphError> {
	let result = panic::catch_unwind(|| {
		let graph_state = &mut *graph_state;
		match graph_state.force_recalculate_graphs(&*user_id) {
			Ok(updates) => {
				let ffi_updates = updates_to_ffi(updates);
				let updates_len = ffi_updates.len();
				let updates_ptr = ManuallyDrop::new(ffi_updates).as_mut_ptr();
				let graph_updates = GraphUpdates { updates: updates_ptr, updates_len };
				FFIResult::new(graph_updates)
			},
			Err(error) => FFIResult::new_mut_error(GraphError::from_error(error)),
		}
	});

	result.unwrap_or_else(|error| {
		FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::Unknown(anyhow::anyhow!(
			"Failed to force recalculate updates from graph: {:?}",
			error
		))))
	})
}

/// Apply actions to graph state
/// # Safety
/// This function is unsafe because it dereferences a raw pointer
/// # Arguments
/// * `graph_state` - a pointer to a graph state
/// * `actions` - a pointer to an array of actions
/// * `actions_len` - the length of the actions array
/// # Returns
/// * `bool` - true if the actions were applied, false otherwise
/// # Errors
/// * `GraphError` - if the actions cannot be applied to the graph state
#[no_mangle]
pub unsafe extern "C" fn graph_apply_actions(
	graph_state: *mut GraphState,
	actions: *const Action,
	actions_len: usize,
	options: *const ActionOptions,
) -> FFIResult<bool, GraphError> {
	let result = panic::catch_unwind(|| {
		if graph_state.is_null() {
			return FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::FFIError(
				"Graph state is null".to_string(),
			)));
		}
		let graph_state = &mut *graph_state;
		let actions = std::slice::from_raw_parts(actions, actions_len);
		let actions = actions_from_ffi(&actions);
		let mut rust_options: Option<ActionOptions> = None;
		if !options.is_null() {
			let options = &*options;
			rust_options = Some(options.clone());
		}
		match graph_state.apply_actions(&actions, &rust_options) {
			Ok(_) => FFIResult::new(true),
			Err(error) => FFIResult::new_mut_error(GraphError::from_error(error)),
		}
	});
	result.unwrap_or_else(|error| {
		FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::Unknown(anyhow::anyhow!(
			"Failed to apply actions to graph: {:?}",
			error
		))))
	})
}

/// Commit pending actions to a graph state
/// # Safety
/// This function is unsafe because it dereferences a raw pointer
/// # Arguments
/// * `graph_state` - a pointer to a graph state
/// # Returns
/// * `void`
/// # Errors
/// * `GraphError` - if the actions cannot be applied to the graph state
#[no_mangle]
pub unsafe extern "C" fn graph_commit(graph_state: *mut GraphState) -> FFIResult<bool, GraphError> {
	let result = panic::catch_unwind(|| {
		if graph_state.is_null() {
			return FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::FFIError(
				"Graph state is null".to_string(),
			)));
		}
		let graph_state = &mut *graph_state;
		graph_state.commit();
		FFIResult::new(true)
	});
	result.unwrap_or_else(|error| {
		FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::Unknown(anyhow::anyhow!(
			"Failed to commit pending changes to graph: {:?}",
			error
		))))
	})
}

/// Rollback pending actions in a graph state
/// # Safety
/// This function is unsafe because it dereferences a raw pointer
/// # Arguments
/// * `graph_state` - a pointer to a graph state
/// # Returns
/// * `void`
/// # Errors
/// * `GraphError` - if the actions cannot be applied to the graph state
#[no_mangle]
pub unsafe extern "C" fn graph_rollback(
	graph_state: *mut GraphState,
) -> FFIResult<bool, GraphError> {
	let result = panic::catch_unwind(|| {
		if graph_state.is_null() {
			return FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::FFIError(
				"Graph state is null".to_string(),
			)));
		}
		let graph_state = &mut *graph_state;
		graph_state.rollback();
		FFIResult::new(true)
	});
	result.unwrap_or_else(|error| {
		FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::Unknown(anyhow::anyhow!(
			"Failed to roll back pending changes in graph: {:?}",
			error
		))))
	})
}

/// Get connections for user from graph state
/// # Safety
/// This function is unsafe because it dereferences a raw pointer
/// # Arguments
/// * `graph_state` - a pointer to a graph state
/// * `user_id` - a pointer to a user id
/// * `schema_id` - a pointer to a schema id
/// * `include_pending` - a boolean to include pending connections
/// # Returns
/// * `GraphConnections` - the pointer to the graph connections
/// # Errors
/// * `GraphError` - if the connections cannot be retrieved
#[no_mangle]
pub unsafe extern "C" fn graph_get_connections_for_user(
	graph_state: *mut GraphState,
	user_id: *const DsnpUserId,
	schema_id: *const SchemaId,
	include_pending: bool,
) -> FFIResult<GraphConnections, GraphError> {
	let result = panic::catch_unwind(|| {
		if graph_state.is_null() {
			return FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::FFIError(
				"Graph state is null".to_string(),
			)));
		}
		let graph_state = &mut *graph_state;
		let user_id = &*user_id;
		let schema_id = &*schema_id;
		match graph_state.get_connections_for_user_graph(user_id, schema_id, include_pending) {
			Ok(connections) => {
				let connections_len = connections.len();
				let connections_ptr = ManuallyDrop::new(connections).as_mut_ptr();
				let graph_connections =
					GraphConnections { connections: connections_ptr, connections_len };
				FFIResult::new(graph_connections)
			},
			Err(error) => FFIResult::new_mut_error(GraphError::from_error(error)),
		}
	});
	result.unwrap_or_else(|error| {
		FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::Unknown(anyhow::anyhow!(
			"Failed get connections for user from graph: {:?}",
			error
		))))
	})
}

/// Get user connections without keys from graph state
/// # Safety
/// This function is unsafe because it dereferences a raw pointer
/// # Arguments
/// * `graph_state` - a pointer to a graph state
/// # Returns
/// * `GraphConnectionsWithoutKeys` - the pointer to the graph connections without keys
/// # Errors
/// * `GraphError` - if the connections cannot be retrieved
#[no_mangle]
pub unsafe extern "C" fn graph_get_connections_without_keys(
	graph_state: *mut GraphState,
) -> FFIResult<GraphConnectionsWithoutKeys, GraphError> {
	let result = panic::catch_unwind(|| {
		if graph_state.is_null() {
			return FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::FFIError(
				"Graph state is null".to_string(),
			)));
		}
		let graph_state = &mut *graph_state;
		match graph_state.get_connections_without_keys() {
			Ok(connections) => {
				let connections_len = connections.len();
				let connections_ptr = ManuallyDrop::new(connections).as_mut_ptr();
				let graph_connections =
					GraphConnectionsWithoutKeys { connections: connections_ptr, connections_len };
				FFIResult::new(graph_connections)
			},
			Err(error) => FFIResult::new_mut_error(GraphError::from_error(error)),
		}
	});
	result.unwrap_or_else(|error| {
		FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::Unknown(anyhow::anyhow!(
			"Failed get connections without keys from graph: {:?}",
			error
		))))
	})
}

/// Get one sided private friendship connections for a user from graph state
/// # Safety
/// This function is unsafe because it dereferences a raw pointer
/// # Arguments
/// * `graph_state` - a pointer to a graph state
/// * `user_id` - a pointer to a user id
/// # Returns
/// * `GraphConnections` - the pointer to the graph connections
/// # Errors
/// * `GraphError` - if the connections cannot be retrieved
#[no_mangle]
pub unsafe extern "C" fn graph_get_one_sided_private_friendship_connections(
	graph_state: *mut GraphState,
	user_id: *const DsnpUserId,
) -> FFIResult<GraphConnections, GraphError> {
	let result = panic::catch_unwind(|| {
		if graph_state.is_null() {
			return FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::FFIError(
				"Graph state is null".to_string(),
			)));
		}
		let graph_state = &mut *graph_state;
		let user_id = &*user_id;
		match graph_state.get_one_sided_private_friendship_connections(user_id) {
			Ok(connections) => {
				let connections_len = connections.len();
				let connections_ptr = ManuallyDrop::new(connections).as_mut_ptr();
				let graph_connections =
					GraphConnections { connections: connections_ptr, connections_len };
				FFIResult::new(graph_connections)
			},
			Err(error) => FFIResult::new_mut_error(GraphError::from_error(error)),
		}
	});
	result.unwrap_or_else(|error| {
		FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::Unknown(anyhow::anyhow!(
			"Failed get one sided private friendship connections from graph: {:?}",
			error
		))))
	})
}

/// Get a list of published and imported public keys associated with a user
/// # Safety
/// This function is unsafe because it dereferences a raw pointer
/// # Arguments
/// * `graph_state` - a pointer to the graph state
/// * `user_id` - a pointer to a user id
/// # Returns
/// * `DsnpPublicKeys` - the pointer to the public keys
/// # Errors
/// * `GraphError` - if the public keys cannot be retrieved
#[no_mangle]
pub unsafe extern "C" fn graph_get_public_keys(
	graph_state: *mut GraphState,
	user_id: *const DsnpUserId,
) -> FFIResult<DsnpPublicKeys, GraphError> {
	let result = panic::catch_unwind(|| {
		if graph_state.is_null() {
			return FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::FFIError(
				"Graph state is null".to_string(),
			)));
		}
		let graph_state = &mut *graph_state;
		let user_id = &*user_id;

		match graph_state.get_public_keys(user_id) {
			Ok(keys) => {
				let ffi_keys = dsnp_public_keys_to_ffi(keys);
				let keys_len = ffi_keys.len();
				let keys_ptr = ManuallyDrop::new(ffi_keys).as_mut_ptr();
				let public_keys = DsnpPublicKeys { keys: keys_ptr, keys_len };
				FFIResult::new(public_keys)
			},
			Err(error) => FFIResult::new_mut_error(GraphError::from_error(error)),
		}
	});
	result.unwrap_or_else(|error| {
		FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::Unknown(anyhow::anyhow!(
			"Failed get public keys from graph: {:?}",
			error
		))))
	})
}

/// Returns the deserialized dsnp keys
/// # Safety
/// This function is unsafe because it dereferences a raw pointer
/// # Arguments
/// * `dsnp_keys` - a pointer to the dsnp keys
/// # Returns
/// * `DsnpPublicKeys` - the pointer to the public keys
/// # Errors
/// * `GraphError` - if the public keys cannot be retrieved
#[no_mangle]
pub unsafe extern "C" fn graph_deserialize_dsnp_keys(
	dsnp_keys: *const DsnpKeys,
) -> FFIResult<DsnpPublicKeys, GraphError> {
	let result = panic::catch_unwind(|| {
		let dsnp_keys = &*dsnp_keys;
		let rust_dsnp_keys = dsnp_keys_from_ffi(dsnp_keys);
		match GraphState::deserialize_dsnp_keys(&Some(rust_dsnp_keys)) {
			Ok(keys) => {
				let ffi_keys = dsnp_public_keys_to_ffi(keys);
				let keys_len = ffi_keys.len();
				let keys_ptr = ManuallyDrop::new(ffi_keys).as_mut_ptr();
				let public_keys = DsnpPublicKeys { keys: keys_ptr, keys_len };
				FFIResult::new(public_keys)
			},
			Err(error) => FFIResult::new_mut_error(GraphError::from_error(error)),
		}
	});
	result.unwrap_or_else(|error| {
		FFIResult::new_mut_error(GraphError::from_error(DsnpGraphError::Unknown(anyhow::anyhow!(
			"Failed to deserialized dsnp keys: {:?}",
			error
		))))
	})
}

/// Free graph state
/// # Arguments
/// * `graph_state` - a pointer to the graph state
#[no_mangle]
pub unsafe extern "C" fn free_graph_state(graph_state: *mut GraphState) {
	let result = panic::catch_unwind(|| {
		if graph_state.is_null() {
			return;
		}
		let mut graph_states = GRAPH_STATES.lock().unwrap();
		let index =
			graph_states.iter().position(|x| x.as_ref() as *const _ == graph_state).unwrap();
		graph_states.remove(index);
	});
	result.unwrap_or(())
}

/// Free GraphStates
/// # Errors
/// * `GraphError` - if the graph states cannot be freed
#[no_mangle]
pub extern "C" fn free_graph_states() {
	let result = panic::catch_unwind(|| {
		let mut graph_states = GRAPH_STATES.lock().unwrap();
		graph_states.clear();
	});
	result.unwrap_or(())
}

/// Free GraphUpdates
/// # Arguments
/// * `graph_updates` - a pointer to the graph updates
#[no_mangle]
pub unsafe extern "C" fn free_graph_updates(graph_updates: *mut GraphUpdates) {
	let result = panic::catch_unwind(|| {
		let _ = Box::from_raw(graph_updates);
	});
	result.unwrap_or(())
}

/// Free GraphConnections
/// # Arguments
/// * `graph_connections` - a pointer to the graph connections
#[no_mangle]
pub unsafe extern "C" fn free_graph_connections(graph_connections: *mut GraphConnections) {
	let result = panic::catch_unwind(|| {
		let _ = Box::from_raw(graph_connections);
	});
	result.unwrap_or(())
}

/// Free GraphConnectionsWithoutKeys
/// # Arguments
/// * `graph_connections` - a pointer to the graph connections
#[no_mangle]
pub unsafe extern "C" fn free_graph_connections_without_keys(
	graph_connections: *mut GraphConnectionsWithoutKeys,
) {
	let result = panic::catch_unwind(|| {
		let _ = Box::from_raw(graph_connections);
	});
	result.unwrap_or(())
}

/// Free DsnpPublicKeys
/// # Arguments
/// * `public_keys` - a pointer to the public keys
#[no_mangle]
pub unsafe extern "C" fn free_graph_dsnp_public_keys(public_keys: *mut DsnpPublicKeys) {
	let result = panic::catch_unwind(|| {
		let _ = Box::from_raw(public_keys);
	});
	result.unwrap_or(())
}

/// Free GraphError
/// # Arguments
/// * `error` - a pointer to the graph error
#[no_mangle]
pub unsafe extern "C" fn free_dsnp_graph_error(error: *mut GraphError) {
	if !error.is_null() {
		unsafe {
			let _ = Box::from_raw(error);
		}
	}
}

/// Get error code from graph error
/// # Arguments
/// * `error` - a pointer to the graph error
/// # Returns
/// * `i32` - the error code or std::i32::MAX
#[no_mangle]
pub unsafe extern "C" fn dsnp_graph_error_code(error: *const GraphError) -> i32 {
	if let Some(error) = unsafe { error.as_ref() } {
		error.error_code()
	} else {
		std::i32::MAX
	}
}

/// Get error message from graph error
/// # Arguments
/// * `error` - a pointer to the graph error
/// # Returns
/// * `*const c_char` - the error message or null
#[no_mangle]
pub unsafe extern "C" fn dsnp_graph_error_message(error: *const GraphError) -> *const c_char {
	if let Some(error) = unsafe { error.as_ref() } {
		let error_msg = CString::new(error.error_message()).unwrap_or_default();
		error_msg.into_raw()
	} else {
		std::ptr::null()
	}
}

/// Free error message
/// # Arguments
/// * `error_message` - a pointer to the error message
#[no_mangle]
pub unsafe extern "C" fn free_dsnp_graph_error_message(error_message: *const c_char) {
	if !error_message.is_null() {
		unsafe {
			let _ = CString::from_raw(error_message as *mut c_char);
		}
	}
}

/// Free graph config
/// # Arguments
/// * `config` - a pointer to the graph config
#[no_mangle]
pub unsafe extern "C" fn free_graph_config(config: *mut Config) {
	let result = panic::catch_unwind(|| {
		let _ = Box::from_raw(config);
	});
	result.unwrap_or(())
}