oxirs-fuseki 0.2.4

SPARQL 1.1/1.2 HTTP protocol server with Fuseki-compatible configuration
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
//! REST API v2
//!
//! Modern RESTful API with OpenAPI 3.0 specification.
//! Provides comprehensive CRUD operations for datasets, queries, and administration.

use crate::config::DatasetConfig;
use crate::server::AppState;
use crate::store_ext::StoreExt;
use anyhow::{Context, Result};
use axum::{
    extract::{Path, Query as AxumQuery, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::{delete, get, post},
    Json, Router,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tracing::{debug, error, info};
use utoipa::{OpenApi, ToSchema};

/// OpenAPI documentation
#[derive(OpenApi)]
#[openapi(
    paths(
        get_api_info,
        list_datasets,
        get_dataset,
        create_dataset,
        delete_dataset,
        execute_query,
        get_triples,
        insert_triple,
        delete_triple,
        get_statistics,
        get_health
    ),
    components(schemas(
        ApiInfo,
        DatasetList,
        Dataset,
        CreateDatasetRequest,
        QueryRequest,
        QueryResponse,
        TripleList,
        Triple,
        InsertTripleRequest,
        DeleteTripleRequest,
        Statistics,
        HealthStatus,
        ErrorResponse
    )),
    tags(
        (name = "info", description = "API information endpoints"),
        (name = "datasets", description = "Dataset management endpoints"),
        (name = "queries", description = "Query execution endpoints"),
        (name = "triples", description = "Triple manipulation endpoints"),
        (name = "statistics", description = "Statistics and monitoring endpoints"),
        (name = "health", description = "Health check endpoints")
    ),
    info(
        title = "OxiRS Fuseki REST API v2",
        version = "2.0.0",
        description = "Modern RESTful API for SPARQL and RDF data management",
        contact(
            name = "OxiRS Team",
            url = "https://github.com/cool-japan/oxirs",
            email = "team@oxirs.dev"
        ),
        license(
            name = "Apache 2.0",
            url = "https://www.apache.org/licenses/LICENSE-2.0"
        )
    ),
    servers(
        (url = "http://localhost:3030/api/v2", description = "Local development"),
        (url = "https://api.oxirs.dev/v2", description = "Production")
    )
)]
pub struct ApiDoc;

/// API information
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct ApiInfo {
    /// API version
    pub version: String,
    /// API name
    pub name: String,
    /// API description
    pub description: String,
    /// Available endpoints
    pub endpoints: Vec<String>,
    /// Supported features
    pub features: Vec<String>,
}

/// Dataset list response
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct DatasetList {
    /// List of datasets
    pub datasets: Vec<Dataset>,
    /// Total count
    pub total: usize,
}

/// Dataset information
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct Dataset {
    /// Dataset name
    pub name: String,
    /// Number of triples
    pub triple_count: usize,
    /// Dataset description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Creation timestamp
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<chrono::DateTime<chrono::Utc>>,
    /// Last modified timestamp
    #[serde(skip_serializing_if = "Option::is_none")]
    pub modified_at: Option<chrono::DateTime<chrono::Utc>>,
}

/// Create dataset request
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct CreateDatasetRequest {
    /// Dataset name
    pub name: String,
    /// Dataset description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Storage type (tdb, memory)
    #[serde(default = "default_storage_type")]
    pub storage_type: String,
}

fn default_storage_type() -> String {
    "tdb".to_string()
}

/// Query request
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct QueryRequest {
    /// SPARQL query string
    pub query: String,
    /// Default graph URIs
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default_graph_uri: Option<Vec<String>>,
    /// Named graph URIs
    #[serde(skip_serializing_if = "Option::is_none")]
    pub named_graph_uri: Option<Vec<String>>,
    /// Query timeout in seconds
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timeout: Option<u64>,
}

/// Query response
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct QueryResponse {
    /// Variable names (for SELECT queries)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub head: Option<QueryHead>,
    /// Query results
    pub results: QueryResults,
    /// Query execution time in milliseconds
    pub execution_time_ms: u64,
}

/// Query head with variable names
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct QueryHead {
    /// Variable names
    pub vars: Vec<String>,
}

/// Query results
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct QueryResults {
    /// Bindings (for SELECT queries)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bindings: Option<Vec<std::collections::HashMap<String, BindingValue>>>,
    /// Boolean result (for ASK queries)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub boolean: Option<bool>,
}

/// Binding value
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct BindingValue {
    /// Value type (uri, literal, bnode)
    #[serde(rename = "type")]
    pub value_type: String,
    /// Value
    pub value: String,
    /// Datatype (for literals)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub datatype: Option<String>,
    /// Language tag (for literals)
    #[serde(skip_serializing_if = "Option::is_none", rename = "xml:lang")]
    pub lang: Option<String>,
}

/// Triple list response
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct TripleList {
    /// List of triples
    pub triples: Vec<Triple>,
    /// Total count
    pub total: usize,
    /// Limit
    pub limit: usize,
    /// Offset
    pub offset: usize,
}

/// RDF Triple
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct Triple {
    /// Subject URI
    pub subject: String,
    /// Predicate URI
    pub predicate: String,
    /// Object (URI or literal)
    pub object: String,
    /// Object type (uri, literal)
    pub object_type: String,
}

/// Insert triple request
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct InsertTripleRequest {
    /// Triples to insert
    pub triples: Vec<Triple>,
    /// Graph URI (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub graph: Option<String>,
}

/// Delete triple request
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct DeleteTripleRequest {
    /// Subject URI (optional, ? for wildcard)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subject: Option<String>,
    /// Predicate URI (optional, ? for wildcard)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub predicate: Option<String>,
    /// Object (optional, ? for wildcard)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub object: Option<String>,
    /// Graph URI (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub graph: Option<String>,
}

/// System statistics
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct Statistics {
    /// Number of datasets
    pub dataset_count: usize,
    /// Total number of triples
    pub total_triples: usize,
    /// Total queries executed
    pub total_queries: u64,
    /// Average query time in milliseconds
    pub avg_query_time_ms: f64,
    /// Uptime in seconds
    pub uptime_seconds: u64,
    /// Memory usage in bytes
    pub memory_usage_bytes: u64,
}

/// Health status
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct HealthStatus {
    /// Overall status
    pub status: String,
    /// Timestamp
    pub timestamp: chrono::DateTime<chrono::Utc>,
    /// Component statuses
    pub components: std::collections::HashMap<String, ComponentHealth>,
}

/// Component health
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct ComponentHealth {
    /// Status (healthy, degraded, unhealthy)
    pub status: String,
    /// Details
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<String>,
}

/// Error response
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct ErrorResponse {
    /// Error code
    pub code: String,
    /// Error message
    pub message: String,
    /// Error details
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<serde_json::Value>,
    /// Timestamp
    pub timestamp: chrono::DateTime<chrono::Utc>,
}

/// Pagination query parameters
#[derive(Debug, Clone, Deserialize, ToSchema, utoipa::IntoParams)]
pub struct PaginationParams {
    /// Limit (default: 100, max: 10000)
    #[serde(default = "default_limit")]
    pub limit: usize,
    /// Offset (default: 0)
    #[serde(default)]
    pub offset: usize,
}

fn default_limit() -> usize {
    100
}

/// API error type
#[derive(Debug)]
pub enum ApiError {
    NotFound(String),
    BadRequest(String),
    InternalError(anyhow::Error),
    Unauthorized,
    Forbidden,
}

impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        let (status, code, message) = match self {
            ApiError::NotFound(msg) => (StatusCode::NOT_FOUND, "NOT_FOUND", msg),
            ApiError::BadRequest(msg) => (StatusCode::BAD_REQUEST, "BAD_REQUEST", msg),
            ApiError::InternalError(err) => (
                StatusCode::INTERNAL_SERVER_ERROR,
                "INTERNAL_ERROR",
                err.to_string(),
            ),
            ApiError::Unauthorized => (
                StatusCode::UNAUTHORIZED,
                "UNAUTHORIZED",
                "Authentication required".to_string(),
            ),
            ApiError::Forbidden => (
                StatusCode::FORBIDDEN,
                "FORBIDDEN",
                "Access denied".to_string(),
            ),
        };

        let error = ErrorResponse {
            code: code.to_string(),
            message,
            details: None,
            timestamp: chrono::Utc::now(),
        };

        (status, Json(error)).into_response()
    }
}

impl From<anyhow::Error> for ApiError {
    fn from(err: anyhow::Error) -> Self {
        ApiError::InternalError(err)
    }
}

/// Get API information
///
/// Returns information about the API version, available endpoints, and features.
#[utoipa::path(
    get,
    path = "/api/v2",
    responses(
        (status = 200, description = "API information", body = ApiInfo)
    ),
    tag = "info"
)]
pub async fn get_api_info() -> Result<Json<ApiInfo>, ApiError> {
    Ok(Json(ApiInfo {
        version: "2.0.0".to_string(),
        name: "OxiRS Fuseki REST API v2".to_string(),
        description: "Modern RESTful API for SPARQL and RDF data management".to_string(),
        endpoints: vec![
            "/api/v2".to_string(),
            "/api/v2/datasets".to_string(),
            "/api/v2/datasets/{name}".to_string(),
            "/api/v2/datasets/{name}/query".to_string(),
            "/api/v2/datasets/{name}/triples".to_string(),
            "/api/v2/statistics".to_string(),
            "/api/v2/health".to_string(),
        ],
        features: vec![
            "SPARQL 1.1".to_string(),
            "SPARQL 1.2".to_string(),
            "RDF-star".to_string(),
            "Federation".to_string(),
            "GraphQL".to_string(),
            "WebSocket".to_string(),
        ],
    }))
}

/// List all datasets
///
/// Returns a list of all available datasets with their metadata.
#[utoipa::path(
    get,
    path = "/api/v2/datasets",
    responses(
        (status = 200, description = "List of datasets", body = DatasetList)
    ),
    tag = "datasets"
)]
pub async fn list_datasets(
    State(state): State<Arc<AppState>>,
) -> Result<Json<DatasetList>, ApiError> {
    let store = &state.store;
    let datasets = store
        .list_datasets()
        .map_err(|e| ApiError::InternalError(e.into()))?;

    let dataset_infos: Vec<Dataset> = datasets
        .into_iter()
        .map(|name| {
            let triple_count = store.count_triples(&name);
            Dataset {
                name,
                triple_count,
                description: None,
                created_at: None,
                modified_at: None,
            }
        })
        .collect();

    let total = dataset_infos.len();

    Ok(Json(DatasetList {
        datasets: dataset_infos,
        total,
    }))
}

/// Get dataset information
///
/// Returns detailed information about a specific dataset.
#[utoipa::path(
    get,
    path = "/api/v2/datasets/{name}",
    responses(
        (status = 200, description = "Dataset information", body = Dataset),
        (status = 404, description = "Dataset not found", body = ErrorResponse)
    ),
    params(
        ("name" = String, Path, description = "Dataset name")
    ),
    tag = "datasets"
)]
pub async fn get_dataset(
    State(state): State<Arc<AppState>>,
    Path(name): Path<String>,
) -> Result<Json<Dataset>, ApiError> {
    let store = &state.store;
    if !store.dataset_exists(&name) {
        return Err(ApiError::NotFound(format!("Dataset '{}' not found", name)));
    }

    let triple_count = store.count_triples(&name);

    Ok(Json(Dataset {
        name,
        triple_count,
        description: None,
        created_at: None,
        modified_at: None,
    }))
}

/// Create a new dataset
///
/// Creates a new dataset with the specified configuration.
#[utoipa::path(
    post,
    path = "/api/v2/datasets",
    request_body = CreateDatasetRequest,
    responses(
        (status = 201, description = "Dataset created", body = Dataset),
        (status = 400, description = "Invalid request", body = ErrorResponse),
        (status = 409, description = "Dataset already exists", body = ErrorResponse)
    ),
    tag = "datasets"
)]
pub async fn create_dataset(
    State(state): State<Arc<AppState>>,
    Json(request): Json<CreateDatasetRequest>,
) -> Result<(StatusCode, Json<Dataset>), ApiError> {
    let store = &state.store;
    if store.dataset_exists(&request.name) {
        return Err(ApiError::BadRequest(format!(
            "Dataset '{}' already exists",
            request.name
        )));
    }

    let config = crate::config::DatasetConfig {
        name: request.name.clone(),
        location: format!("./data/{}", request.name),
        read_only: false,
        text_index: None,
        shacl_shapes: Vec::new(),
        services: Vec::new(),
        access_control: None,
        backup: None,
    };

    store
        .create_dataset(&request.name, config)
        .map_err(|e| ApiError::InternalError(e.into()))?;

    info!("Created dataset: {}", request.name);

    Ok((
        StatusCode::CREATED,
        Json(Dataset {
            name: request.name,
            triple_count: 0,
            description: request.description,
            created_at: Some(chrono::Utc::now()),
            modified_at: Some(chrono::Utc::now()),
        }),
    ))
}

/// Delete a dataset
///
/// Deletes the specified dataset and all its triples.
#[utoipa::path(
    delete,
    path = "/api/v2/datasets/{name}",
    responses(
        (status = 204, description = "Dataset deleted"),
        (status = 404, description = "Dataset not found", body = ErrorResponse)
    ),
    params(
        ("name" = String, Path, description = "Dataset name")
    ),
    tag = "datasets"
)]
pub async fn delete_dataset(
    State(state): State<Arc<AppState>>,
    Path(name): Path<String>,
) -> Result<StatusCode, ApiError> {
    let store = &state.store;
    if !store.dataset_exists(&name) {
        return Err(ApiError::NotFound(format!("Dataset '{}' not found", name)));
    }

    store
        .remove_dataset(&name)
        .map_err(|e| ApiError::InternalError(anyhow::anyhow!("{}", e)))?;

    info!("Deleted dataset: {}", name);

    Ok(StatusCode::NO_CONTENT)
}

/// Execute a SPARQL query
///
/// Executes a SPARQL query against the specified dataset.
#[utoipa::path(
    post,
    path = "/api/v2/datasets/{name}/query",
    request_body = QueryRequest,
    responses(
        (status = 200, description = "Query results", body = QueryResponse),
        (status = 400, description = "Invalid query", body = ErrorResponse),
        (status = 404, description = "Dataset not found", body = ErrorResponse)
    ),
    params(
        ("name" = String, Path, description = "Dataset name")
    ),
    tag = "queries"
)]
pub async fn execute_query(
    State(state): State<Arc<AppState>>,
    Path(name): Path<String>,
    Json(request): Json<QueryRequest>,
) -> Result<Json<QueryResponse>, ApiError> {
    let store = &state.store;
    if !store.dataset_exists(&name) {
        return Err(ApiError::NotFound(format!("Dataset '{}' not found", name)));
    }

    let start = std::time::Instant::now();

    let results = store
        .query_dataset(&request.query, Some(&name))
        .map_err(|e| ApiError::BadRequest(format!("Query execution failed: {}", e)))?;

    let execution_time_ms = start.elapsed().as_millis() as u64;

    // Convert results to API format
    let bindings = match results.inner {
        oxirs_core::query::QueryResult::Select { bindings, .. } => bindings
            .into_iter()
            .map(|binding| {
                binding
                    .into_iter()
                    .map(|(var, value)| {
                        (
                            var,
                            BindingValue {
                                value_type: "uri".to_string(), // Simplified
                                value: value.to_string(),
                                datatype: None,
                                lang: None,
                            },
                        )
                    })
                    .collect()
            })
            .collect(),
        _ => Vec::new(), // Handle other query types
    };

    Ok(Json(QueryResponse {
        head: Some(QueryHead {
            vars: vec![], // Would extract from query
        }),
        results: QueryResults {
            bindings: Some(bindings),
            boolean: None,
        },
        execution_time_ms,
    }))
}

/// Get triples from a dataset
///
/// Retrieves triples matching the specified pattern.
#[utoipa::path(
    get,
    path = "/api/v2/datasets/{name}/triples",
    responses(
        (status = 200, description = "List of triples", body = TripleList),
        (status = 404, description = "Dataset not found", body = ErrorResponse)
    ),
    params(
        ("name" = String, Path, description = "Dataset name"),
        PaginationParams
    ),
    tag = "triples"
)]
pub async fn get_triples(
    State(state): State<Arc<AppState>>,
    Path(name): Path<String>,
    AxumQuery(pagination): AxumQuery<PaginationParams>,
) -> Result<Json<TripleList>, ApiError> {
    let store = &state.store;
    if !store.dataset_exists(&name) {
        return Err(ApiError::NotFound(format!("Dataset '{}' not found", name)));
    }

    // Build SPARQL query to get triples
    let query = format!(
        "SELECT ?s ?p ?o WHERE {{ ?s ?p ?o }} LIMIT {} OFFSET {}",
        pagination.limit, pagination.offset
    );

    let results = store
        .query_dataset(&query, Some(&name))
        .map_err(|e| ApiError::InternalError(anyhow::anyhow!("{}", e)))?;

    let triples: Vec<Triple> = match results.inner {
        oxirs_core::query::QueryResult::Select { bindings, .. } => bindings
            .into_iter()
            .map(|binding| Triple {
                subject: binding.get("s").map(|t| t.to_string()).unwrap_or_default(),
                predicate: binding.get("p").map(|t| t.to_string()).unwrap_or_default(),
                object: binding.get("o").map(|t| t.to_string()).unwrap_or_default(),
                object_type: "uri".to_string(), // Simplified
            })
            .collect(),
        _ => Vec::new(), // Handle other query types
    };

    let total = store.count_triples(&name);

    Ok(Json(TripleList {
        triples,
        total,
        limit: pagination.limit,
        offset: pagination.offset,
    }))
}

/// Insert triples into a dataset
///
/// Inserts one or more triples into the specified dataset.
#[utoipa::path(
    post,
    path = "/api/v2/datasets/{name}/triples",
    request_body = InsertTripleRequest,
    responses(
        (status = 201, description = "Triples inserted"),
        (status = 400, description = "Invalid request", body = ErrorResponse),
        (status = 404, description = "Dataset not found", body = ErrorResponse)
    ),
    params(
        ("name" = String, Path, description = "Dataset name")
    ),
    tag = "triples"
)]
pub async fn insert_triple(
    State(state): State<Arc<AppState>>,
    Path(name): Path<String>,
    Json(request): Json<InsertTripleRequest>,
) -> Result<StatusCode, ApiError> {
    let store = &state.store;
    if !store.dataset_exists(&name) {
        return Err(ApiError::NotFound(format!("Dataset '{}' not found", name)));
    }

    // Build SPARQL INSERT query
    let triples_str = request
        .triples
        .iter()
        .map(|t| format!("<{}> <{}> <{}> .", t.subject, t.predicate, t.object))
        .collect::<Vec<_>>()
        .join(" ");

    let query = format!("INSERT DATA {{ {} }}", triples_str);

    store
        .update_dataset(&query, Some(&name))
        .map_err(|e| ApiError::BadRequest(format!("Insert failed: {}", e)))?;

    info!(
        "Inserted {} triples into dataset: {}",
        request.triples.len(),
        name
    );

    Ok(StatusCode::CREATED)
}

/// Delete triples from a dataset
///
/// Deletes triples matching the specified pattern.
#[utoipa::path(
    delete,
    path = "/api/v2/datasets/{name}/triples",
    request_body = DeleteTripleRequest,
    responses(
        (status = 204, description = "Triples deleted"),
        (status = 400, description = "Invalid request", body = ErrorResponse),
        (status = 404, description = "Dataset not found", body = ErrorResponse)
    ),
    params(
        ("name" = String, Path, description = "Dataset name")
    ),
    tag = "triples"
)]
pub async fn delete_triple(
    State(state): State<Arc<AppState>>,
    Path(name): Path<String>,
    Json(request): Json<DeleteTripleRequest>,
) -> Result<StatusCode, ApiError> {
    let store = &state.store;
    if !store.dataset_exists(&name) {
        return Err(ApiError::NotFound(format!("Dataset '{}' not found", name)));
    }

    // Build SPARQL DELETE query
    let s = request.subject.as_deref().unwrap_or("?s");
    let p = request.predicate.as_deref().unwrap_or("?p");
    let o = request.object.as_deref().unwrap_or("?o");

    let query = format!("DELETE WHERE {{ {} {} {} }}", s, p, o);

    store
        .update_dataset(&query, Some(&name))
        .map_err(|e| ApiError::BadRequest(format!("Delete failed: {}", e)))?;

    info!("Deleted triples from dataset: {}", name);

    Ok(StatusCode::NO_CONTENT)
}

/// Get system statistics
///
/// Returns statistics about the system and its performance.
#[utoipa::path(
    get,
    path = "/api/v2/statistics",
    responses(
        (status = 200, description = "System statistics", body = Statistics)
    ),
    tag = "statistics"
)]
pub async fn get_statistics(
    State(state): State<Arc<AppState>>,
) -> Result<Json<Statistics>, ApiError> {
    let store = &state.store;
    let datasets = store.list_datasets().unwrap_or_default();
    let total_triples: usize = datasets.iter().map(|ds| store.count_triples(ds)).sum();

    Ok(Json(Statistics {
        dataset_count: datasets.len(),
        total_triples,
        total_queries: 0, // Would need metrics integration
        avg_query_time_ms: 0.0,
        uptime_seconds: 0,     // Would need startup time tracking
        memory_usage_bytes: 0, // Would need system metrics
    }))
}

/// Health check
///
/// Returns the health status of the system and its components.
#[utoipa::path(
    get,
    path = "/api/v2/health",
    responses(
        (status = 200, description = "Health status", body = HealthStatus)
    ),
    tag = "health"
)]
pub async fn get_health(
    State(state): State<Arc<AppState>>,
) -> Result<Json<HealthStatus>, ApiError> {
    let store = &state.store;
    let mut components = std::collections::HashMap::new();

    // Check store health
    let store_status = if store.list_datasets().is_ok() {
        ComponentHealth {
            status: "healthy".to_string(),
            details: None,
        }
    } else {
        ComponentHealth {
            status: "unhealthy".to_string(),
            details: Some("Failed to access store".to_string()),
        }
    };
    components.insert("store".to_string(), store_status);

    let overall_status = if components.values().all(|c| c.status == "healthy") {
        "healthy"
    } else {
        "degraded"
    };

    Ok(Json(HealthStatus {
        status: overall_status.to_string(),
        timestamp: chrono::Utc::now(),
        components,
    }))
}

/// Register REST API v2 routes
///
/// Adds all REST API v2 endpoints to the provided router.
pub fn register_routes(router: Router<Arc<AppState>>) -> Router<Arc<AppState>> {
    router
        // Info
        .route("/api/v2", get(get_api_info))
        // Datasets
        .route("/api/v2/datasets", get(list_datasets).post(create_dataset))
        .route(
            "/api/v2/datasets/:name",
            get(get_dataset).delete(delete_dataset),
        )
        // Queries
        .route("/api/v2/datasets/:name/query", post(execute_query))
        // Triples
        .route(
            "/api/v2/datasets/:name/triples",
            get(get_triples).post(insert_triple).delete(delete_triple),
        )
        // Statistics and health
        .route("/api/v2/statistics", get(get_statistics))
        .route("/api/v2/health", get(get_health))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_api_info_serialization() {
        let info = ApiInfo {
            version: "2.0.0".to_string(),
            name: "Test API".to_string(),
            description: "Test".to_string(),
            endpoints: vec![],
            features: vec![],
        };

        let json = serde_json::to_string(&info).unwrap();
        assert!(json.contains("2.0.0"));
    }

    #[test]
    fn test_error_response() {
        let error = ErrorResponse {
            code: "TEST_ERROR".to_string(),
            message: "Test error".to_string(),
            details: None,
            timestamp: chrono::Utc::now(),
        };

        assert_eq!(error.code, "TEST_ERROR");
    }
}