cloudillo-types 0.8.13

Shared types, adapter traits, and error types for the Cloudillo federated collaboration platform
Documentation
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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
// SPDX-FileCopyrightText: Szilárd Hajba
// SPDX-License-Identifier: LGPL-3.0-or-later

//! Common types used throughout the Cloudillo platform.

use crate::abac::AttrSet;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_with::skip_serializing_none;
use std::collections::HashMap;
use std::time::SystemTime;

// TnId //
//******//
//pub type TnId = u32;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct TnId(pub u32);

impl std::fmt::Display for TnId {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		write!(f, "{}", self.0)
	}
}

impl Serialize for TnId {
	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
	where
		S: serde::Serializer,
	{
		serializer.serialize_u32(self.0)
	}
}

impl<'de> Deserialize<'de> for TnId {
	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
	where
		D: serde::Deserializer<'de>,
	{
		Ok(TnId(u32::deserialize(deserializer)?))
	}
}

// Timestamp //
//***********//
//pub type Timestamp = u32;
#[derive(Clone, Copy, Debug, Default)]
pub struct Timestamp(pub i64);

impl Timestamp {
	pub fn now() -> Timestamp {
		let res = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap_or_default();
		Timestamp(res.as_secs().cast_signed())
	}

	pub fn from_now(delta: i64) -> Timestamp {
		let res = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap_or_default();
		Timestamp(res.as_secs().cast_signed() + delta)
	}

	/// Add seconds to this timestamp
	pub fn add_seconds(&self, seconds: i64) -> Timestamp {
		Timestamp(self.0 + seconds)
	}

	/// Format as ISO 8601 string (e.g. "2024-01-15T12:00:00Z")
	pub fn to_iso_string(&self) -> String {
		use chrono::{DateTime, SecondsFormat};
		DateTime::from_timestamp(self.0, 0)
			.unwrap_or_default()
			.to_rfc3339_opts(SecondsFormat::Secs, true)
	}
}

impl std::fmt::Display for Timestamp {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		write!(f, "{}", self.0)
	}
}

impl std::cmp::PartialEq for Timestamp {
	fn eq(&self, other: &Self) -> bool {
		self.0 == other.0
	}
}

impl std::cmp::PartialOrd for Timestamp {
	fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
		Some(self.cmp(other))
	}
}

impl std::cmp::Eq for Timestamp {}

impl std::cmp::Ord for Timestamp {
	fn cmp(&self, other: &Self) -> std::cmp::Ordering {
		self.0.cmp(&other.0)
	}
}

impl Serialize for Timestamp {
	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
	where
		S: serde::Serializer,
	{
		serializer.serialize_i64(self.0)
	}
}

impl<'de> Deserialize<'de> for Timestamp {
	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
	where
		D: serde::Deserializer<'de>,
	{
		use serde::de::{Error, Visitor};

		struct TimestampVisitor;

		impl Visitor<'_> for TimestampVisitor {
			type Value = Timestamp;

			fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
				write!(f, "an integer timestamp or ISO 8601 string")
			}

			fn visit_i64<E: Error>(self, v: i64) -> Result<Self::Value, E> {
				Ok(Timestamp(v))
			}

			fn visit_u64<E: Error>(self, v: u64) -> Result<Self::Value, E> {
				Ok(Timestamp(v.cast_signed()))
			}

			fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> {
				use chrono::DateTime;
				DateTime::parse_from_rfc3339(v)
					.map(|dt| Timestamp(dt.timestamp()))
					.map_err(|_| E::custom("invalid ISO 8601 timestamp"))
			}
		}

		deserializer.deserialize_any(TimestampVisitor)
	}
}

/// Serialize Timestamp as ISO 8601 string for API responses
pub fn serialize_timestamp_iso<S>(ts: &Timestamp, serializer: S) -> Result<S::Ok, S::Error>
where
	S: Serializer,
{
	use chrono::{DateTime, SecondsFormat};
	let dt = DateTime::from_timestamp(ts.0, 0).unwrap_or_default();
	serializer.serialize_str(&dt.to_rfc3339_opts(SecondsFormat::Secs, true))
}

/// Serialize Option<Timestamp> as ISO 8601 string for API responses
pub fn serialize_timestamp_iso_opt<S>(
	ts: &Option<Timestamp>,
	serializer: S,
) -> Result<S::Ok, S::Error>
where
	S: Serializer,
{
	match ts {
		Some(ts) => serialize_timestamp_iso(ts, serializer),
		None => serializer.serialize_none(),
	}
}

// Patch<T> - For PATCH semantics //
//**********************************//
/// Represents a field in a PATCH request with three states:
/// - `Undefined`: Field not present in JSON - don't change existing value
/// - `Null`: Field present with null value - set to NULL in database
/// - `Value(T)`: Field present with value - update to this value
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Patch<T> {
	/// Field not present in request - no change
	#[default]
	Undefined,
	/// Field present with null value - delete/set to NULL
	Null,
	/// Field present with value - update to this value
	Value(T),
}

impl<T> Patch<T> {
	/// Returns true if this is `Undefined`
	pub fn is_undefined(&self) -> bool {
		matches!(self, Patch::Undefined)
	}

	/// Returns true if this is `Null`
	pub fn is_null(&self) -> bool {
		matches!(self, Patch::Null)
	}

	/// Returns true if this is `Value(_)`
	pub fn is_value(&self) -> bool {
		matches!(self, Patch::Value(_))
	}

	/// Returns the value if `Value`, otherwise None
	pub fn value(&self) -> Option<&T> {
		match self {
			Patch::Value(v) => Some(v),
			_ => None,
		}
	}

	/// Converts to Option: Undefined -> None, Null -> Some(None), Value(v) -> Some(Some(v))
	pub fn as_option(&self) -> Option<Option<&T>> {
		match self {
			Patch::Undefined => None,
			Patch::Null => Some(None),
			Patch::Value(v) => Some(Some(v)),
		}
	}

	/// Maps a `Patch<T>` to `Patch<U>` by applying a function to the contained value
	pub fn map<U, F>(self, f: F) -> Patch<U>
	where
		F: FnOnce(T) -> U,
	{
		match self {
			Patch::Undefined => Patch::Undefined,
			Patch::Null => Patch::Null,
			Patch::Value(v) => Patch::Value(f(v)),
		}
	}
}

impl<T> Serialize for Patch<T>
where
	T: Serialize,
{
	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
	where
		S: Serializer,
	{
		match self {
			Patch::Undefined | Patch::Null => serializer.serialize_none(),
			Patch::Value(v) => v.serialize(serializer),
		}
	}
}

impl<'de, T> Deserialize<'de> for Patch<T>
where
	T: Deserialize<'de>,
{
	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
	where
		D: Deserializer<'de>,
	{
		Option::<T>::deserialize(deserializer).map(|opt| match opt {
			None => Patch::Null,
			Some(v) => Patch::Value(v),
		})
	}
}

// Phase 1: Authentication & Profile Types
//******************************************

/// Registration type and verification request
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RegisterVerifyCheckRequest {
	#[serde(rename = "type")]
	pub typ: String, // "idp" or "domain"
	pub id_tag: String,
	pub app_domain: Option<String>,
	pub token: Option<String>, // Optional: Required for unauthenticated requests
}

/// Registration request with account creation
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RegisterRequest {
	#[serde(rename = "type")]
	pub typ: String, // "idp" or "domain"
	pub id_tag: String,
	pub app_domain: Option<String>,
	pub email: String,
	pub token: String,
	pub lang: Option<String>,
}

/// Registration verification request (legacy, kept for compatibility)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RegisterVerifyRequest {
	pub id_tag: String,
	pub token: String,
}

/// Public profile wire type for federated profile exchange
#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Profile {
	pub id_tag: String,
	pub name: String,
	#[serde(rename = "type")]
	pub r#type: String,
	pub profile_pic: Option<String>,
	pub cover_pic: Option<String>,
	pub keys: Vec<crate::auth_adapter::AuthKey>,
	/// Extensible metadata (profile sections, tab config, etc.)
	pub x: Option<HashMap<String, String>>,
}

/// Terse self-profile shape returned by `/api/me`.
///
/// Used for server-to-server federation sync (base profile fields + signing
/// keys). Deliberately omits the `x` extension map that `Profile` carries —
/// peers don't need tier-filtered UI metadata.
#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProfileBase {
	pub id_tag: String,
	pub name: String,
	#[serde(rename = "type")]
	pub r#type: String,
	pub profile_pic: Option<String>,
	pub keys: Vec<crate::auth_adapter::AuthKey>,
}

/// Profile patch for PATCH /me endpoint
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProfilePatch {
	#[serde(default)]
	pub name: Patch<String>,
	/// Extensible metadata fields (partial merge: existing keys preserved, null deletes)
	#[serde(default)]
	pub x: Option<HashMap<String, Option<String>>>,
}

/// Admin profile patch for PATCH /admin/profile/:idTag endpoint
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdminProfilePatch {
	// Basic profile fields
	#[serde(default)]
	pub name: Patch<String>,

	// Administrative fields
	#[serde(default)]
	pub roles: Patch<Option<Vec<String>>>,
	#[serde(default)]
	pub status: Patch<crate::meta_adapter::ProfileStatus>,
}

/// Profile information response
#[skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProfileInfo {
	pub id_tag: String,
	pub name: String,
	#[serde(rename = "type")]
	pub r#type: Option<String>,
	pub profile_pic: Option<String>, // file_id
	pub status: Option<crate::meta_adapter::ProfileStatus>,
	pub connected: Option<bool>,
	pub following: Option<bool>,
	/// Per-profile trust preference controlling proxy-token use on passive reads.
	/// `"always"` = always authenticate, `"never"` = never, absent = ask.
	pub trust: Option<crate::meta_adapter::ProfileTrust>,
	pub roles: Option<Vec<String>>,
	#[serde(
		serialize_with = "serialize_timestamp_iso_opt",
		skip_serializing_if = "Option::is_none"
	)]
	pub created_at: Option<Timestamp>,
	/// Extensible metadata (profile sections, tab config, etc.)
	pub x: Option<HashMap<String, String>>,
}

/// Request body for community profile creation
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateCommunityRequest {
	#[serde(rename = "type")]
	pub typ: String, // "idp" or "domain" - identity type
	pub name: Option<String>,
	pub profile_pic: Option<String>,
	pub app_domain: Option<String>, // For domain type
	pub invite_ref: Option<String>, // Invite ref code for community creation
}

/// Response for community profile creation
#[skip_serializing_none]
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CommunityProfileResponse {
	pub id_tag: String,
	pub name: String,
	#[serde(rename = "type")]
	pub r#type: String,
	pub profile_pic: Option<String>,
	#[serde(serialize_with = "serialize_timestamp_iso")]
	pub created_at: Timestamp,
	/// Initial value of the new community tenant's `ui.onboarding` setting.
	/// `Some("verify-idp")` for an IDP-typed community whose IDP identity is
	/// still pending; `None` for domain-typed (or already-active) communities.
	/// The frontend uses this to decide whether to mark the community as
	/// pending in the sidebar and show the activation banner.
	pub onboarding: Option<String>,
}

// Phase 2: Action Management & File Integration
//***********************************************

/// Action creation request
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateActionRequest {
	#[serde(rename = "type")]
	pub r#type: String, // "Create", "Update", etc
	pub sub_type: Option<String>, // "Note", "Image", etc
	pub parent_id: Option<String>,
	// Note: root_id is auto-populated from parent chain, not specified by clients
	pub content: String,
	pub attachments: Option<Vec<String>>, // file_ids
	pub audience: Option<Vec<String>>,
}

/// Action response (API layer)
#[skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ActionResponse {
	pub action_id: String,
	pub action_token: String,
	#[serde(rename = "type")]
	pub r#type: String,
	pub sub_type: Option<String>,
	pub parent_id: Option<String>,
	pub root_id: Option<String>,
	pub content: String,
	pub attachments: Vec<String>,
	pub issuer_tag: String,
	#[serde(serialize_with = "serialize_timestamp_iso")]
	pub created_at: Timestamp,
}

/// List actions query parameters
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListActionsQuery {
	#[serde(rename = "type")]
	pub r#type: Option<String>,
	pub parent_id: Option<String>,
	pub offset: Option<usize>,
	pub limit: Option<usize>,
}

/// File upload response
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FileUploadResponse {
	pub file_id: String,
	pub descriptor: String,
	pub variants: Vec<FileVariantInfo>,
}

/// File variant information
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FileVariantInfo {
	pub variant_id: String,
	pub format: String,
	pub size: u64,
	pub resolution: Option<(u32, u32)>,
}

/// Tag information with optional usage count
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TagInfo {
	pub tag: String,
	#[serde(skip_serializing_if = "Option::is_none")]
	pub count: Option<u32>,
}

// Phase 1: API Response Envelope & Error Types
//***********************************************

/// Pagination information for list responses (offset-based - deprecated)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaginationInfo {
	pub offset: usize,
	pub limit: usize,
	pub total: usize,
}

/// Cursor-based pagination information for list responses
///
/// Provides stable pagination that handles data changes between requests.
/// The cursor is an opaque base64-encoded JSON containing sort field, value, and last item ID.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CursorPaginationInfo {
	/// Opaque cursor for fetching next page (None if no more results)
	pub next_cursor: Option<String>,
	/// Whether more results are available
	pub has_more: bool,
}

/// Cursor data structure (encoded as base64 JSON in API)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CursorData {
	/// Sort field: "created", "modified", "recent", "name"
	pub s: String,
	/// Sort value (timestamp as i64 or string for name)
	pub v: serde_json::Value,
	/// Last item's external ID (file_id or action_id)
	pub id: String,
}

impl CursorData {
	/// Create a new cursor from sort field, value, and item ID
	pub fn new(sort_field: &str, sort_value: serde_json::Value, item_id: &str) -> Self {
		Self { s: sort_field.to_string(), v: sort_value, id: item_id.to_string() }
	}

	/// Encode cursor to base64 string
	pub fn encode(&self) -> String {
		use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
		let json = serde_json::to_string(self).unwrap_or_default();
		URL_SAFE_NO_PAD.encode(json.as_bytes())
	}

	/// Decode cursor from base64 string
	pub fn decode(cursor: &str) -> Option<Self> {
		use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
		let bytes = URL_SAFE_NO_PAD.decode(cursor).ok()?;
		let json = String::from_utf8(bytes).ok()?;
		serde_json::from_str(&json).ok()
	}

	/// Get sort value as i64 timestamp (for date fields)
	pub fn timestamp(&self) -> Option<i64> {
		self.v.as_i64()
	}

	/// Get sort value as string (for name field)
	pub fn string_value(&self) -> Option<&str> {
		self.v.as_str()
	}
}

/// Success response envelope for single objects
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApiResponse<T> {
	pub data: T,
	#[serde(skip_serializing_if = "Option::is_none")]
	pub pagination: Option<PaginationInfo>,
	#[serde(skip_serializing_if = "Option::is_none")]
	pub cursor_pagination: Option<CursorPaginationInfo>,
	#[serde(serialize_with = "serialize_timestamp_iso")]
	pub time: Timestamp,
	#[serde(skip_serializing_if = "Option::is_none")]
	pub req_id: Option<String>,
}

impl<T> ApiResponse<T> {
	/// Create a new response with data and current time
	pub fn new(data: T) -> Self {
		Self {
			data,
			pagination: None,
			cursor_pagination: None,
			time: Timestamp::now(),
			req_id: None,
		}
	}

	/// Create a response with offset-based pagination info (deprecated)
	pub fn with_pagination(data: T, offset: usize, limit: usize, total: usize) -> Self {
		Self {
			data,
			pagination: Some(PaginationInfo { offset, limit, total }),
			cursor_pagination: None,
			time: Timestamp::now(),
			req_id: None,
		}
	}

	/// Create a response with cursor-based pagination
	pub fn with_cursor_pagination(data: T, next_cursor: Option<String>, has_more: bool) -> Self {
		Self {
			data,
			pagination: None,
			cursor_pagination: Some(CursorPaginationInfo { next_cursor, has_more }),
			time: Timestamp::now(),
			req_id: None,
		}
	}

	/// Add request ID to response
	pub fn with_req_id(mut self, req_id: String) -> Self {
		self.req_id = Some(req_id);
		self
	}
}

/// Error response format
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorResponse {
	pub error: ErrorDetails,
}

/// Error details with structured code and message
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorDetails {
	pub code: String,
	pub message: String,
	#[serde(skip_serializing_if = "Option::is_none")]
	pub details: Option<serde_json::Value>,
}

impl ErrorResponse {
	/// Create a new error response with code and message
	pub fn new(code: String, message: String) -> Self {
		Self { error: ErrorDetails { code, message, details: None } }
	}

	/// Add additional details to error
	pub fn with_details(mut self, details: serde_json::Value) -> Self {
		self.error.details = Some(details);
		self
	}
}

// ABAC Permission System Types
//*****************************

/// Access level enum for files
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "lowercase")]
pub enum AccessLevel {
	None,
	Read,
	Comment,
	Write,
	Admin,
}

impl AccessLevel {
	pub fn as_str(&self) -> &'static str {
		match self {
			Self::None => "none",
			Self::Read => "read",
			Self::Comment => "comment",
			Self::Write => "write",
			Self::Admin => "admin",
		}
	}

	/// Return the lesser of two access levels.
	/// Ordering: None < Read < Comment < Write < Admin
	pub fn min(self, other: Self) -> Self {
		match (self, other) {
			(Self::None, _) | (_, Self::None) => Self::None,
			(Self::Read, _) | (_, Self::Read) => Self::Read,
			(Self::Comment, _) | (_, Self::Comment) => Self::Comment,
			(Self::Write, _) | (_, Self::Write) => Self::Write,
			(Self::Admin, Self::Admin) => Self::Admin,
		}
	}

	/// Return the greater of two access levels.
	/// Ordering: None < Read < Comment < Write < Admin
	pub fn max(self, other: Self) -> Self {
		match (self, other) {
			(Self::Admin, _) | (_, Self::Admin) => Self::Admin,
			(Self::Write, _) | (_, Self::Write) => Self::Write,
			(Self::Comment, _) | (_, Self::Comment) => Self::Comment,
			(Self::Read, _) | (_, Self::Read) => Self::Read,
			(Self::None, Self::None) => Self::None,
		}
	}

	/// Convert a share permission char ('R', 'C', 'W', 'A') to an access level.
	/// 'A' (admin) maps to Write because scoped tokens don't carry admin privileges;
	/// admin access is only resolved from direct ownership, not from share links.
	/// Unknown chars default to Read.
	pub fn from_perm_char(c: char) -> Self {
		match c {
			'W' | 'A' => Self::Write,
			'C' => Self::Comment,
			_ => Self::Read,
		}
	}
}

/// Token scope for scoped access tokens (e.g., share links)
///
/// Format in JWT: "file:{file_id}:{R|C|W}"
/// This enum provides type-safe parsing instead of manual string splitting.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TokenScope {
	/// File-scoped access with specific access level
	File { file_id: String, access: AccessLevel },
	/// APKG publish scope — restricts to package upload and APKG action creation
	ApkgPublish,
}

impl TokenScope {
	/// Parse a scope string into a typed TokenScope
	///
	/// Supported formats:
	/// - "file:{file_id}:R" -> File scope with Read access
	/// - "file:{file_id}:C" -> File scope with Comment access
	/// - "file:{file_id}:W" -> File scope with Write access
	pub fn parse(s: &str) -> Option<Self> {
		if s == "apkg:publish" {
			return Some(Self::ApkgPublish);
		}
		let parts: Vec<&str> = s.split(':').collect();
		if parts.len() == 3 && parts[0] == "file" {
			let access = match parts[2] {
				"W" => AccessLevel::Write,
				"C" => AccessLevel::Comment,
				_ => AccessLevel::Read, // "R" or any other value defaults to Read
			};
			return Some(Self::File { file_id: parts[1].to_string(), access });
		}
		None
	}

	/// Get file ID if this is a file scope
	pub fn file_id(&self) -> Option<&str> {
		match self {
			Self::File { file_id, .. } => Some(file_id),
			Self::ApkgPublish => None,
		}
	}

	/// Get access level if this is a file scope
	pub fn file_access(&self) -> Option<AccessLevel> {
		match self {
			Self::File { access, .. } => Some(*access),
			Self::ApkgPublish => None,
		}
	}

	/// Check if scope matches a specific file
	pub fn matches_file(&self, target_file_id: &str) -> bool {
		match self {
			Self::File { file_id, .. } => file_id == target_file_id,
			Self::ApkgPublish => false,
		}
	}
}

/// Profile attributes for ABAC
#[derive(Debug, Clone)]
pub struct ProfileAttrs {
	pub id_tag: Box<str>,
	pub profile_type: Box<str>,
	pub tenant_tag: Box<str>,
	pub roles: Vec<Box<str>>,
	pub status: Box<str>,
	pub following: bool,
	pub connected: bool,
	pub visibility: Box<str>,
}

impl AttrSet for ProfileAttrs {
	fn get(&self, key: &str) -> Option<&str> {
		match key {
			"id_tag" => Some(&self.id_tag),
			"profile_type" => Some(&self.profile_type),
			"tenant_tag" | "owner_id_tag" => Some(&self.tenant_tag),
			"status" => Some(&self.status),
			"following" => Some(if self.following { "true" } else { "false" }),
			"connected" => Some(if self.connected { "true" } else { "false" }),
			"visibility" => Some(&self.visibility),
			_ => None,
		}
	}

	fn get_list(&self, key: &str) -> Option<Vec<&str>> {
		match key {
			"roles" => Some(self.roles.iter().map(AsRef::as_ref).collect()),
			_ => None,
		}
	}
}

/// Action attributes for ABAC
#[derive(Debug, Clone)]
pub struct ActionAttrs {
	pub typ: Box<str>,
	pub sub_typ: Option<Box<str>>,
	/// The tenant/instance where this action is stored (NOT the creator - see issuer_id_tag)
	pub tenant_id_tag: Box<str>,
	/// The original creator/sender of the action
	pub issuer_id_tag: Box<str>,
	pub parent_id: Option<Box<str>>,
	pub root_id: Option<Box<str>>,
	pub audience_tag: Vec<Box<str>>,
	pub tags: Vec<Box<str>>,
	pub visibility: Box<str>,
	/// Whether the subject follows the action issuer
	pub following: bool,
	/// Whether the subject is connected (mutual) with the action issuer
	pub connected: bool,
}

impl AttrSet for ActionAttrs {
	fn get(&self, key: &str) -> Option<&str> {
		match key {
			"type" => Some(&self.typ),
			"sub_type" => self.sub_typ.as_deref(),
			// Support both old and new names for backward compat with ABAC rules
			"tenant_id_tag" | "owner_id_tag" => Some(&self.tenant_id_tag),
			"issuer_id_tag" => Some(&self.issuer_id_tag),
			"parent_id" => self.parent_id.as_deref(),
			"root_id" => self.root_id.as_deref(),
			"visibility" => Some(&self.visibility),
			"following" => Some(if self.following { "true" } else { "false" }),
			"connected" => Some(if self.connected { "true" } else { "false" }),
			_ => None,
		}
	}

	fn get_list(&self, key: &str) -> Option<Vec<&str>> {
		match key {
			"audience_tag" => Some(self.audience_tag.iter().map(AsRef::as_ref).collect()),
			"tags" => Some(self.tags.iter().map(AsRef::as_ref).collect()),
			_ => None,
		}
	}
}

/// File attributes for ABAC
#[derive(Debug, Clone)]
pub struct FileAttrs {
	pub file_id: Box<str>,
	pub owner_id_tag: Box<str>,
	pub mime_type: Box<str>,
	pub tags: Vec<Box<str>>,
	pub visibility: Box<str>,
	pub access_level: AccessLevel,
	/// Whether the subject follows the file owner
	pub following: bool,
	/// Whether the subject is connected (mutual) with the file owner
	pub connected: bool,
}

impl AttrSet for FileAttrs {
	fn get(&self, key: &str) -> Option<&str> {
		match key {
			"file_id" => Some(&self.file_id),
			"owner_id_tag" => Some(&self.owner_id_tag),
			"mime_type" => Some(&self.mime_type),
			"visibility" => Some(&self.visibility),
			"access_level" => Some(self.access_level.as_str()),
			"following" => Some(if self.following { "true" } else { "false" }),
			"connected" => Some(if self.connected { "true" } else { "false" }),
			_ => None,
		}
	}

	fn get_list(&self, key: &str) -> Option<Vec<&str>> {
		match key {
			"tags" => Some(self.tags.iter().map(AsRef::as_ref).collect()),
			_ => None,
		}
	}
}

/// Subject attributes for ABAC (CREATE operations)
///
/// Used to evaluate collection-level permissions for operations
/// that don't yet have a specific object (like file upload, post creation).
#[derive(Debug, Clone)]
pub struct SubjectAttrs {
	pub id_tag: Box<str>,
	pub roles: Vec<Box<str>>,
	pub tier: Box<str>,                  // "free", "standard", "premium"
	pub quota_remaining_bytes: Box<str>, // in bytes, as string for ABAC
	pub rate_limit_remaining: Box<str>,  // per hour, as string for ABAC
	pub banned: bool,
	pub email_verified: bool,
}

impl AttrSet for SubjectAttrs {
	fn get(&self, key: &str) -> Option<&str> {
		match key {
			"id_tag" => Some(&self.id_tag),
			"tier" => Some(&self.tier),
			"quota_remaining" | "quota_remaining_bytes" => Some(&self.quota_remaining_bytes),
			"rate_limit_remaining" => Some(&self.rate_limit_remaining),
			"banned" => Some(if self.banned { "true" } else { "false" }),
			"email_verified" => Some(if self.email_verified { "true" } else { "false" }),
			_ => None,
		}
	}

	fn get_list(&self, key: &str) -> Option<Vec<&str>> {
		match key {
			"roles" => Some(self.roles.iter().map(AsRef::as_ref).collect()),
			_ => None,
		}
	}
}

// vim: ts=4