reinhardt-views 0.1.2

View layer aggregator for viewsets and views-core
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
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
use crate::viewsets::actions::Action;
use crate::viewsets::filtering_support::{FilterConfig, FilterableViewSet, OrderingConfig};
use crate::viewsets::handler::ModelViewSetHandler;
use crate::viewsets::metadata::{ActionMetadata, get_actions_for_viewset};
use crate::viewsets::middleware::ViewSetMiddleware;
use crate::viewsets::pagination_support::{PaginatedViewSet, PaginationConfig};
use async_trait::async_trait;
use hyper::Method;
use reinhardt_auth::Permission;
use reinhardt_db::orm::{Model, query_types::DbBackend};
use reinhardt_http::{Request, Response, Result};
use reinhardt_rest::filters::FilterBackend;
use reinhardt_rest::serializers::Serializer;
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::collections::HashMap;
use std::marker::PhantomData;
use std::sync::Arc;

/// Extract the primary key value from request path parameters by lookup field
/// name. Returns a JSON string value suitable for `ModelViewSetHandler` methods.
fn extract_pk(request: &Request, lookup_field: &str) -> Result<serde_json::Value> {
	request
		.path_params
		.get(lookup_field)
		.map(|v| serde_json::Value::String(v.clone()))
		.ok_or_else(|| {
			reinhardt_core::exception::Error::Http(format!(
				"Missing path parameter: {}",
				lookup_field
			))
		})
}

/// Create a `MethodNotAllowed` error for the given HTTP method.
fn method_not_allowed(method: &Method) -> reinhardt_core::exception::Error {
	reinhardt_core::exception::Error::MethodNotAllowed(format!("Method {} not allowed", method))
}

/// ViewSet trait - similar to Django REST Framework's ViewSet
/// Uses composition of mixins instead of inheritance
#[async_trait]
pub trait ViewSet: Send + Sync {
	/// Get the basename for URL routing
	fn get_basename(&self) -> &str;

	/// Get the lookup field for detail routes
	/// Defaults to "id" if not overridden
	fn get_lookup_field(&self) -> &str {
		"id"
	}

	/// Dispatch request to appropriate action
	async fn dispatch(&self, request: Request, action: Action) -> Result<Response>;

	/// Dispatch request with dependency injection context
	///
	/// Get extra actions defined on this ViewSet
	/// Returns custom actions decorated with `#[action]` or manually registered
	fn get_extra_actions(&self) -> Vec<ActionMetadata> {
		let viewset_type = std::any::type_name::<Self>();

		// Try inventory-based registration first
		let mut actions = get_actions_for_viewset(viewset_type);

		// Also check manual registration
		let manual_actions = crate::viewsets::registry::get_registered_actions(viewset_type);
		actions.extend(manual_actions);

		actions
	}

	/// Get URL map for extra actions
	/// Returns empty map for uninitialized ViewSets
	fn get_extra_action_url_map(&self) -> HashMap<String, String> {
		HashMap::new()
	}

	/// Get current base URL (only available after initialization)
	fn get_current_base_url(&self) -> Option<String> {
		None
	}

	/// Reverse an action name to a URL
	fn reverse_action(&self, _action_name: &str, _args: &[&str]) -> Result<String> {
		Err(reinhardt_core::exception::Error::NotFound(
			"ViewSet not bound to router".to_string(),
		))
	}

	/// Get middleware for this ViewSet
	/// Returns None if no middleware is configured
	fn get_middleware(&self) -> Option<Arc<dyn ViewSetMiddleware>> {
		None
	}

	/// Check if login is required for this ViewSet
	fn requires_login(&self) -> bool {
		false
	}

	/// Get required permissions for this ViewSet
	fn get_required_permissions(&self) -> Vec<String> {
		Vec::new()
	}
}

/// Generic ViewSet without built-in CRUD logic.
///
/// `GenericViewSet<T>` is an extensibility hook for users who want to build a
/// `ViewSet` from scratch with their own dispatch logic. It does **not**
/// perform any CRUD by itself; calling `dispatch()` on a bare `GenericViewSet`
/// always returns a `NotFound` error with guidance pointing to the correct
/// abstractions.
///
/// # Choosing the right ViewSet
///
/// - For automatic CRUD against a database `Model`, use [`ModelViewSet`].
/// - For read-only access (list + retrieve only), use [`ReadOnlyModelViewSet`].
/// - For fully custom behavior, define your own type and `impl ViewSet for YourType`
///   with a hand-written `dispatch()`. `GenericViewSet` is rarely the right choice.
///
/// # Example: composing a custom ViewSet via the builder
///
/// ```
/// use reinhardt_views::viewsets::{GenericViewSet, ViewSet};
///
/// let viewset = GenericViewSet::new("widgets", ());
/// assert_eq!(viewset.get_basename(), "widgets");
/// ```
// Allow dead_code: generic container for composable ViewSet implementations via trait bounds
#[allow(dead_code)]
#[derive(Clone)]
pub struct GenericViewSet<T> {
	basename: String,
	handler: T,
}

impl<T: 'static> GenericViewSet<T> {
	/// Creates a new `GenericViewSet` with the given basename and handler.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_views::viewsets::{GenericViewSet, ViewSet};
	///
	/// let viewset = GenericViewSet::new("users", ());
	/// assert_eq!(viewset.get_basename(), "users");
	/// ```
	pub fn new(basename: impl Into<String>, handler: T) -> Self {
		Self {
			basename: basename.into(),
			handler,
		}
	}

	/// Convert ViewSet to Handler with action mapping
	/// Returns a ViewSetBuilder for configuration
	///
	/// # Examples
	///
	/// ```ignore
	/// use reinhardt_views::{viewset_actions, viewsets::GenericViewSet};
	/// use hyper::Method;
	///
	/// let viewset = GenericViewSet::new("users", ());
	/// let actions = viewset_actions!(GET => "list");
	/// let handler = viewset.as_view().with_actions(actions).build();
	/// ```
	pub fn as_view(self) -> crate::viewsets::builder::ViewSetBuilder<Self>
	where
		T: Send + Sync,
	{
		crate::viewsets::builder::ViewSetBuilder::new(self)
	}
}

#[async_trait]
impl<T: Send + Sync> ViewSet for GenericViewSet<T> {
	fn get_basename(&self) -> &str {
		&self.basename
	}

	async fn dispatch(&self, _request: Request, action: Action) -> Result<Response> {
		// `GenericViewSet` carries no built-in CRUD logic on purpose. Users who
		// reach this point typically need one of the concrete ViewSets that *do*
		// implement CRUD, or a hand-written `impl ViewSet` on their own type.
		// Returning a guidance-rich error avoids silent placeholder responses
		// (the regression class behind issue #3985).
		Err(reinhardt_core::exception::Error::NotFound(format!(
			"GenericViewSet has no built-in CRUD logic for action {:?}. \
			 For real CRUD, use ModelViewSet<M, S> or ReadOnlyModelViewSet<M, S>. \
			 To implement custom logic, define your own struct and \
			 `impl ViewSet for YourType` with a hand-written dispatch().",
			action.action_type
		)))
	}
}

/// `ModelViewSet` - combines all CRUD mixins, backed by a real
/// [`ModelViewSetHandler`] for database-backed CRUD.
///
/// Similar to Django REST Framework's `ModelViewSet` but built around Rust
/// type composition. `dispatch()` routes the standard REST verbs to the
/// embedded handler's `list` / `retrieve` / `create` / `update` / `destroy`
/// methods, so registering a `ModelViewSet` with a router yields actual
/// model-backed responses (not placeholders).
pub struct ModelViewSet<M, S>
where
	M: Model + Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
	S: Send + Sync + 'static,
{
	basename: String,
	lookup_field: String,
	pagination_config: Option<PaginationConfig>,
	filter_config: Option<FilterConfig>,
	ordering_config: Option<OrderingConfig>,
	handler: ModelViewSetHandler<M>,
	_serializer: PhantomData<S>,
}

// Implement FilterableViewSet for ModelViewSet
impl<M, S> FilterableViewSet for ModelViewSet<M, S>
where
	M: Model + Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
	S: Send + Sync + 'static,
{
	fn get_filter_config(&self) -> Option<FilterConfig> {
		self.filter_config.clone()
	}

	fn get_ordering_config(&self) -> Option<OrderingConfig> {
		self.ordering_config.clone()
	}
}

impl<M, S> ModelViewSet<M, S>
where
	M: Model + Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
	S: Send + Sync + 'static,
{
	/// Creates a new `ModelViewSet` with the given basename.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_views::viewsets::{ModelViewSet, ViewSet};
	/// use reinhardt_db::prelude::Model;
	/// use serde::{Serialize, Deserialize};
	///
	/// #[derive(Serialize, Deserialize, Clone, Debug)]
	/// struct User {
	///     id: Option<i64>,
	///     username: String,
	/// }
	///
	/// #[derive(Clone)]
	/// struct UserFields;
	///
	/// impl reinhardt_db::orm::FieldSelector for UserFields {
	///     fn with_alias(self, _alias: &str) -> Self { self }
	/// }
	///
	/// impl Model for User {
	///     type PrimaryKey = i64;
	///     type Fields = UserFields;
	///     fn table_name() -> &'static str { "users" }
	///     fn primary_key(&self) -> Option<Self::PrimaryKey> { self.id }
	///     fn set_primary_key(&mut self, value: Self::PrimaryKey) { self.id = Some(value); }
	///     fn new_fields() -> Self::Fields { UserFields }
	/// }
	///
	/// let viewset = ModelViewSet::<User, reinhardt_rest::serializers::JsonSerializer<User>>::new("users");
	/// assert_eq!(viewset.get_basename(), "users");
	/// ```
	pub fn new(basename: impl Into<String>) -> Self {
		Self {
			basename: basename.into(),
			lookup_field: "id".to_string(),
			pagination_config: Some(PaginationConfig::default()),
			filter_config: None,
			ordering_config: None,
			handler: ModelViewSetHandler::<M>::new(),
			_serializer: PhantomData,
		}
	}

	/// Set custom lookup field for this ViewSet
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_views::viewsets::{ModelViewSet, ViewSet};
	/// use reinhardt_db::prelude::Model;
	/// use serde::{Serialize, Deserialize};
	///
	/// #[derive(Serialize, Deserialize, Clone, Debug)]
	/// struct User {
	///     id: Option<i64>,
	///     username: String,
	/// }
	///
	/// #[derive(Clone)]
	/// struct UserFields;
	///
	/// impl reinhardt_db::orm::FieldSelector for UserFields {
	///     fn with_alias(self, _alias: &str) -> Self { self }
	/// }
	///
	/// impl Model for User {
	///     type PrimaryKey = i64;
	///     type Fields = UserFields;
	///     fn table_name() -> &'static str { "users" }
	///     fn primary_key(&self) -> Option<Self::PrimaryKey> { self.id }
	///     fn set_primary_key(&mut self, value: Self::PrimaryKey) { self.id = Some(value); }
	///     fn new_fields() -> Self::Fields { UserFields }
	/// }
	///
	/// let viewset = ModelViewSet::<User, ()>::new("users")
	///     .with_lookup_field("username");
	/// assert_eq!(viewset.get_lookup_field(), "username");
	/// ```
	pub fn with_lookup_field(mut self, field: impl Into<String>) -> Self {
		self.lookup_field = field.into();
		self
	}

	/// Set pagination configuration for this ViewSet
	///
	/// # Examples
	///
	/// ```
	/// # use reinhardt_views::viewsets::{ModelViewSet, PaginationConfig};
	/// # use reinhardt_db::orm::{FieldSelector, Model};
	/// # use serde::{Deserialize, Serialize};
	/// # #[derive(Clone, Serialize, Deserialize)]
	/// # struct Item { id: Option<i64> }
	/// # #[derive(Clone)] struct ItemFields;
	/// # impl FieldSelector for ItemFields { fn with_alias(self, _: &str) -> Self { self } }
	/// # impl Model for Item {
	/// #     type PrimaryKey = i64; type Fields = ItemFields;
	/// #     fn table_name() -> &'static str { "items" }
	/// #     fn primary_key(&self) -> Option<i64> { self.id }
	/// #     fn set_primary_key(&mut self, v: i64) { self.id = Some(v); }
	/// #     fn new_fields() -> Self::Fields { ItemFields }
	/// # }
	/// // Page number pagination with custom page size
	/// let viewset = ModelViewSet::<Item, ()>::new("items")
	///     .with_pagination(PaginationConfig::page_number(20, Some(100)));
	///
	/// // Limit/offset pagination
	/// let viewset = ModelViewSet::<Item, ()>::new("items")
	///     .with_pagination(PaginationConfig::limit_offset(25, Some(500)));
	///
	/// // Disable pagination
	/// let viewset = ModelViewSet::<Item, ()>::new("items")
	///     .with_pagination(PaginationConfig::none());
	/// ```
	pub fn with_pagination(mut self, config: PaginationConfig) -> Self {
		self.pagination_config = Some(config);
		self
	}

	/// Disable pagination for this ViewSet
	///
	/// # Examples
	///
	/// ```
	/// # use reinhardt_views::viewsets::ModelViewSet;
	/// # use reinhardt_db::orm::{FieldSelector, Model};
	/// # use serde::{Deserialize, Serialize};
	/// # #[derive(Clone, Serialize, Deserialize)]
	/// # struct Item { id: Option<i64> }
	/// # #[derive(Clone)] struct ItemFields;
	/// # impl FieldSelector for ItemFields { fn with_alias(self, _: &str) -> Self { self } }
	/// # impl Model for Item {
	/// #     type PrimaryKey = i64; type Fields = ItemFields;
	/// #     fn table_name() -> &'static str { "items" }
	/// #     fn primary_key(&self) -> Option<i64> { self.id }
	/// #     fn set_primary_key(&mut self, v: i64) { self.id = Some(v); }
	/// #     fn new_fields() -> Self::Fields { ItemFields }
	/// # }
	/// let viewset = ModelViewSet::<Item, ()>::new("items")
	///     .without_pagination();
	/// ```
	pub fn without_pagination(mut self) -> Self {
		self.pagination_config = None;
		self
	}

	/// Set filter configuration for this ViewSet
	///
	/// # Examples
	///
	/// ```
	/// # use reinhardt_views::viewsets::{ModelViewSet, FilterConfig};
	/// # use reinhardt_db::orm::{FieldSelector, Model};
	/// # use serde::{Deserialize, Serialize};
	/// # #[derive(Clone, Serialize, Deserialize)]
	/// # struct Item { id: Option<i64> }
	/// # #[derive(Clone)] struct ItemFields;
	/// # impl FieldSelector for ItemFields { fn with_alias(self, _: &str) -> Self { self } }
	/// # impl Model for Item {
	/// #     type PrimaryKey = i64; type Fields = ItemFields;
	/// #     fn table_name() -> &'static str { "items" }
	/// #     fn primary_key(&self) -> Option<i64> { self.id }
	/// #     fn set_primary_key(&mut self, v: i64) { self.id = Some(v); }
	/// #     fn new_fields() -> Self::Fields { ItemFields }
	/// # }
	/// let viewset = ModelViewSet::<Item, ()>::new("items")
	///     .with_filters(
	///         FilterConfig::new()
	///             .with_filterable_fields(vec!["status", "category"])
	///             .with_search_fields(vec!["title", "description"])
	///     );
	/// ```
	pub fn with_filters(mut self, config: FilterConfig) -> Self {
		self.filter_config = Some(config);
		self
	}

	/// Set ordering configuration for this ViewSet
	///
	/// # Examples
	///
	/// ```
	/// # use reinhardt_views::viewsets::{ModelViewSet, OrderingConfig};
	/// # use reinhardt_db::orm::{FieldSelector, Model};
	/// # use serde::{Deserialize, Serialize};
	/// # #[derive(Clone, Serialize, Deserialize)]
	/// # struct Item { id: Option<i64> }
	/// # #[derive(Clone)] struct ItemFields;
	/// # impl FieldSelector for ItemFields { fn with_alias(self, _: &str) -> Self { self } }
	/// # impl Model for Item {
	/// #     type PrimaryKey = i64; type Fields = ItemFields;
	/// #     fn table_name() -> &'static str { "items" }
	/// #     fn primary_key(&self) -> Option<i64> { self.id }
	/// #     fn set_primary_key(&mut self, v: i64) { self.id = Some(v); }
	/// #     fn new_fields() -> Self::Fields { ItemFields }
	/// # }
	/// let viewset = ModelViewSet::<Item, ()>::new("items")
	///     .with_ordering(
	///         OrderingConfig::new()
	///             .with_ordering_fields(vec!["created_at", "title", "id"])
	///             .with_default_ordering(vec!["-created_at"])
	///     );
	/// ```
	pub fn with_ordering(mut self, config: OrderingConfig) -> Self {
		self.ordering_config = Some(config);
		self
	}

	/// Set the database connection pool used by CRUD handlers.
	///
	/// Without a pool, list/retrieve fall back to the in-memory queryset (if
	/// any), and create/update/destroy will operate only on the queryset.
	pub fn with_pool(mut self, pool: Arc<sqlx::AnyPool>) -> Self {
		self.handler = std::mem::take(&mut self.handler).with_pool(pool);
		self
	}

	/// Set the database backend type (PostgreSQL, MySQL, SQLite).
	pub fn with_db_backend(mut self, backend: DbBackend) -> Self {
		self.handler = std::mem::take(&mut self.handler).with_db_backend(backend);
		self
	}

	/// Set a custom serializer used by CRUD handlers.
	pub fn with_serializer(
		mut self,
		serializer: Arc<dyn Serializer<Input = M, Output = String> + Send + Sync>,
	) -> Self {
		self.handler = std::mem::take(&mut self.handler).with_serializer(serializer);
		self
	}

	/// Provide an in-memory queryset used when no database pool is set.
	pub fn with_queryset(mut self, items: Vec<M>) -> Self {
		self.handler = std::mem::take(&mut self.handler).with_queryset(items);
		self
	}

	/// Add a permission class enforced before each request.
	pub fn add_permission(mut self, permission: Arc<dyn Permission>) -> Self {
		self.handler = std::mem::take(&mut self.handler).add_permission(permission);
		self
	}

	/// Add a filter backend applied to list requests.
	pub fn add_filter_backend(mut self, backend: Arc<dyn FilterBackend>) -> Self {
		self.handler = std::mem::take(&mut self.handler).add_filter_backend(backend);
		self
	}

	/// Convert ViewSet to Handler with action mapping
	/// Returns a ViewSetBuilder for configuration
	pub fn as_view(self) -> crate::viewsets::builder::ViewSetBuilder<Self> {
		crate::viewsets::builder::ViewSetBuilder::new(self)
	}
}

#[async_trait]
impl<M, S> ViewSet for ModelViewSet<M, S>
where
	M: Model + Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
	S: Send + Sync + 'static,
{
	fn get_basename(&self) -> &str {
		&self.basename
	}

	fn get_lookup_field(&self) -> &str {
		&self.lookup_field
	}

	async fn dispatch(&self, request: Request, action: Action) -> Result<Response> {
		// Route to the embedded `ModelViewSetHandler<M>` for real CRUD.
		// Path params have already been populated by the router using the
		// `lookup_field` placeholder, e.g. `/items/{id}/`.
		match (request.method.clone(), action.detail) {
			(Method::GET, false) => self.handler.list(&request).await.map_err(Into::into),
			(Method::POST, false) => self.handler.create(&request).await.map_err(Into::into),
			(Method::GET, true) => {
				let pk = extract_pk(&request, &self.lookup_field)?;
				self.handler
					.retrieve(&request, pk)
					.await
					.map_err(Into::into)
			}
			(Method::PUT, true) | (Method::PATCH, true) => {
				let pk = extract_pk(&request, &self.lookup_field)?;
				self.handler.update(&request, pk).await.map_err(Into::into)
			}
			(Method::DELETE, true) => {
				let pk = extract_pk(&request, &self.lookup_field)?;
				self.handler.destroy(&request, pk).await.map_err(Into::into)
			}
			_ => Err(method_not_allowed(&request.method)),
		}
	}
}

// Implement PaginatedViewSet for ModelViewSet
impl<M, S> PaginatedViewSet for ModelViewSet<M, S>
where
	M: Model + Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
	S: Send + Sync + 'static,
{
	fn get_pagination_config(&self) -> Option<PaginationConfig> {
		self.pagination_config.clone()
	}
}

/// `ReadOnlyModelViewSet` - exposes only `list` and `retrieve` against a real
/// [`ModelViewSetHandler`].
///
/// Other HTTP verbs (POST/PUT/PATCH/DELETE) return `MethodNotAllowed`.
pub struct ReadOnlyModelViewSet<M, S>
where
	M: Model + Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
	S: Send + Sync + 'static,
{
	basename: String,
	lookup_field: String,
	pagination_config: Option<PaginationConfig>,
	filter_config: Option<FilterConfig>,
	ordering_config: Option<OrderingConfig>,
	handler: ModelViewSetHandler<M>,
	_serializer: PhantomData<S>,
}

impl<M, S> ReadOnlyModelViewSet<M, S>
where
	M: Model + Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
	S: Send + Sync + 'static,
{
	/// Creates a new `ReadOnlyModelViewSet` with the given basename.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_views::viewsets::{ReadOnlyModelViewSet, ViewSet};
	/// use reinhardt_db::prelude::Model;
	/// use serde::{Serialize, Deserialize};
	///
	/// #[derive(Serialize, Deserialize, Clone, Debug)]
	/// struct User {
	///     id: Option<i64>,
	///     username: String,
	/// }
	///
	/// #[derive(Clone)]
	/// struct UserFields;
	///
	/// impl reinhardt_db::orm::FieldSelector for UserFields {
	///     fn with_alias(self, _alias: &str) -> Self { self }
	/// }
	///
	/// impl Model for User {
	///     type PrimaryKey = i64;
	///     type Fields = UserFields;
	///     fn table_name() -> &'static str { "users" }
	///     fn primary_key(&self) -> Option<Self::PrimaryKey> { self.id }
	///     fn set_primary_key(&mut self, value: Self::PrimaryKey) { self.id = Some(value); }
	///     fn new_fields() -> Self::Fields { UserFields }
	/// }
	///
	/// let viewset = ReadOnlyModelViewSet::<User, reinhardt_rest::serializers::JsonSerializer<User>>::new("users");
	/// assert_eq!(viewset.get_basename(), "users");
	/// ```
	pub fn new(basename: impl Into<String>) -> Self {
		Self {
			basename: basename.into(),
			lookup_field: "id".to_string(),
			pagination_config: Some(PaginationConfig::default()),
			filter_config: None,
			ordering_config: None,
			handler: ModelViewSetHandler::<M>::new(),
			_serializer: PhantomData,
		}
	}

	/// Set custom lookup field for this ViewSet
	pub fn with_lookup_field(mut self, field: impl Into<String>) -> Self {
		self.lookup_field = field.into();
		self
	}

	/// Set pagination configuration for this ViewSet
	pub fn with_pagination(mut self, config: PaginationConfig) -> Self {
		self.pagination_config = Some(config);
		self
	}

	/// Disable pagination for this ViewSet
	pub fn without_pagination(mut self) -> Self {
		self.pagination_config = None;
		self
	}

	/// Set filter configuration for this ViewSet
	///
	/// # Examples
	///
	/// ```ignore
	/// use reinhardt_views::viewsets::{ReadOnlyModelViewSet, FilterConfig};
	///
	/// let viewset = ReadOnlyModelViewSet::<MyModel, MySerializer>::new("items")
	///     .with_filters(
	///         FilterConfig::new()
	///             .with_filterable_fields(vec!["status", "category"])
	///             .with_search_fields(vec!["title", "description"])
	///     );
	/// ```
	pub fn with_filters(mut self, config: FilterConfig) -> Self {
		self.filter_config = Some(config);
		self
	}

	/// Set ordering configuration for this ViewSet
	///
	/// # Examples
	///
	/// ```ignore
	/// use reinhardt_views::viewsets::{ReadOnlyModelViewSet, OrderingConfig};
	///
	/// let viewset = ReadOnlyModelViewSet::<MyModel, MySerializer>::new("items")
	///     .with_ordering(
	///         OrderingConfig::new()
	///             .with_ordering_fields(vec!["created_at", "title"])
	///             .with_default_ordering(vec!["-created_at"])
	///     );
	/// ```
	pub fn with_ordering(mut self, config: OrderingConfig) -> Self {
		self.ordering_config = Some(config);
		self
	}

	/// Set the database connection pool used by read handlers.
	pub fn with_pool(mut self, pool: Arc<sqlx::AnyPool>) -> Self {
		self.handler = std::mem::take(&mut self.handler).with_pool(pool);
		self
	}

	/// Set the database backend type (PostgreSQL, MySQL, SQLite).
	pub fn with_db_backend(mut self, backend: DbBackend) -> Self {
		self.handler = std::mem::take(&mut self.handler).with_db_backend(backend);
		self
	}

	/// Set a custom serializer used by read handlers.
	pub fn with_serializer(
		mut self,
		serializer: Arc<dyn Serializer<Input = M, Output = String> + Send + Sync>,
	) -> Self {
		self.handler = std::mem::take(&mut self.handler).with_serializer(serializer);
		self
	}

	/// Provide an in-memory queryset used when no database pool is set.
	pub fn with_queryset(mut self, items: Vec<M>) -> Self {
		self.handler = std::mem::take(&mut self.handler).with_queryset(items);
		self
	}

	/// Add a permission class enforced before each request.
	pub fn add_permission(mut self, permission: Arc<dyn Permission>) -> Self {
		self.handler = std::mem::take(&mut self.handler).add_permission(permission);
		self
	}

	/// Add a filter backend applied to list requests.
	pub fn add_filter_backend(mut self, backend: Arc<dyn FilterBackend>) -> Self {
		self.handler = std::mem::take(&mut self.handler).add_filter_backend(backend);
		self
	}

	/// Convert ViewSet to Handler with action mapping
	/// Returns a ViewSetBuilder for configuration
	pub fn as_view(self) -> crate::viewsets::builder::ViewSetBuilder<Self> {
		crate::viewsets::builder::ViewSetBuilder::new(self)
	}
}

#[async_trait]
impl<M, S> ViewSet for ReadOnlyModelViewSet<M, S>
where
	M: Model + Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
	S: Send + Sync + 'static,
{
	fn get_basename(&self) -> &str {
		&self.basename
	}

	fn get_lookup_field(&self) -> &str {
		&self.lookup_field
	}

	async fn dispatch(&self, request: Request, action: Action) -> Result<Response> {
		match (request.method.clone(), action.detail) {
			(Method::GET, false) => self.handler.list(&request).await.map_err(Into::into),
			(Method::GET, true) => {
				let pk = extract_pk(&request, &self.lookup_field)?;
				self.handler
					.retrieve(&request, pk)
					.await
					.map_err(Into::into)
			}
			_ => Err(method_not_allowed(&request.method)),
		}
	}
}

// Implement PaginatedViewSet for ReadOnlyModelViewSet
impl<M, S> PaginatedViewSet for ReadOnlyModelViewSet<M, S>
where
	M: Model + Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
	S: Send + Sync + 'static,
{
	fn get_pagination_config(&self) -> Option<PaginationConfig> {
		self.pagination_config.clone()
	}
}

// Implement FilterableViewSet for ReadOnlyModelViewSet
impl<M, S> FilterableViewSet for ReadOnlyModelViewSet<M, S>
where
	M: Model + Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
	S: Send + Sync + 'static,
{
	fn get_filter_config(&self) -> Option<FilterConfig> {
		self.filter_config.clone()
	}

	fn get_ordering_config(&self) -> Option<OrderingConfig> {
		self.ordering_config.clone()
	}
}

// Manually re-assert the `UnwindSafe` / `RefUnwindSafe` auto traits for the
// public viewset structs. The new `Arc<dyn Serializer ...>` / `Arc<dyn
// Permission>` / `Arc<dyn FilterBackend>` fields introduced by this PR do
// not propagate these markers because trait objects do not implement them
// by default, which would otherwise surface as cargo-semver-checks
// `auto_trait_impl_removed` under the RC phase's no-breaking-change policy.
// The trait objects are only accessed via `&self` / `Arc::clone`, and the
// `Send + Sync` supertraits already guarantee thread safety, so manually
// re-implementing the markers preserves the pre-PR public-API contract.
impl<M, S> std::panic::UnwindSafe for ModelViewSet<M, S>
where
	M: Model + Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
	S: Send + Sync + 'static,
{
}
impl<M, S> std::panic::RefUnwindSafe for ModelViewSet<M, S>
where
	M: Model + Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
	S: Send + Sync + 'static,
{
}

impl<M, S> std::panic::UnwindSafe for ReadOnlyModelViewSet<M, S>
where
	M: Model + Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
	S: Send + Sync + 'static,
{
}
impl<M, S> std::panic::RefUnwindSafe for ReadOnlyModelViewSet<M, S>
where
	M: Model + Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
	S: Send + Sync + 'static,
{
}

#[cfg(test)]
mod tests {
	use super::*;
	use hyper::Method;
	use reinhardt_db::orm::{FieldSelector, Model};
	use serde::{Deserialize, Serialize};
	use std::collections::HashMap;
	use std::sync::Arc;

	/// Minimal `Model` implementation used to satisfy the `ModelViewSet` trait
	/// bounds in unit tests. The previous tests used `ModelViewSet::<(), ()>`,
	/// but bare `()` does not implement `Model` once the bounds were tightened.
	#[derive(Debug, Clone, Serialize, Deserialize)]
	struct DummyModel {
		id: Option<i64>,
	}

	#[derive(Clone)]
	struct DummyFields;

	impl FieldSelector for DummyFields {
		fn with_alias(self, _alias: &str) -> Self {
			self
		}
	}

	impl Model for DummyModel {
		type PrimaryKey = i64;
		type Fields = DummyFields;
		fn table_name() -> &'static str {
			"dummy"
		}
		fn primary_key(&self) -> Option<Self::PrimaryKey> {
			self.id
		}
		fn set_primary_key(&mut self, value: Self::PrimaryKey) {
			self.id = Some(value);
		}
		fn new_fields() -> Self::Fields {
			DummyFields
		}
	}

	#[tokio::test]
	async fn test_viewset_builder_validation_empty_actions() {
		let viewset = ModelViewSet::<DummyModel, ()>::new("test");
		let builder = viewset.as_view();

		// Test that empty actions causes build to fail
		let result = builder.build();
		assert!(result.is_err());

		// Check error message without unwrapping
		match result {
			Err(e) => assert!(
				e.to_string()
					.contains("The `actions` argument must be provided")
			),
			Ok(_) => panic!("Expected error but got success"),
		}
	}

	#[tokio::test]
	async fn test_viewset_builder_name_suffix_mutual_exclusivity() {
		let viewset = ModelViewSet::<DummyModel, ()>::new("test");
		let builder = viewset.as_view();

		// Test that providing both name and suffix fails
		let result = builder
			.with_name("test_name")
			.and_then(|b| b.with_suffix("test_suffix"));

		assert!(result.is_err());

		// Check error message without unwrapping
		match result {
			Err(e) => assert!(e.to_string().contains("received both `name` and `suffix`")),
			Ok(_) => panic!("Expected error but got success"),
		}
	}

	#[tokio::test]
	async fn test_viewset_builder_successful_build() {
		let viewset = ModelViewSet::<DummyModel, ()>::new("test");
		let mut actions = HashMap::new();
		actions.insert(Method::GET, "list".to_string());

		let builder = viewset.as_view();
		let result = builder.with_actions(actions).build();

		let handler = result.unwrap();

		// Test that handler is created successfully
		// Handler should be created without errors
		assert!(Arc::strong_count(&handler) > 0);
	}

	#[tokio::test]
	async fn test_viewset_builder_with_name() {
		let viewset = ModelViewSet::<DummyModel, ()>::new("test");
		let mut actions = HashMap::new();
		actions.insert(Method::GET, "list".to_string());

		let builder = viewset.as_view();
		let result = builder
			.with_actions(actions)
			.with_name("test_view")
			.and_then(|b| b.build());

		assert!(result.is_ok());
	}

	#[tokio::test]
	async fn test_viewset_builder_with_suffix() {
		let viewset = ModelViewSet::<DummyModel, ()>::new("test");
		let mut actions = HashMap::new();
		actions.insert(Method::GET, "list".to_string());

		let builder = viewset.as_view();
		let result = builder
			.with_actions(actions)
			.with_suffix("_list")
			.and_then(|b| b.build());

		assert!(result.is_ok());
	}
}