summaryrefslogblamecommitdiff
path: root/makima/src/server/handlers/chains.rs
blob: ae19ca0295a4486565c6b4eb68757da37e205014 (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050














                                                                                            

                                                                                                

                                                                                 















































































































































































































































































































































































































































































































































































































                                                                                                    






















































































































































































































































































































































































































































                                                                                                          
                                                                                              

















                                                                                 
                                          








                                                                             




                                                             
























































                                                                                               
                                    











                                                                           



























































































































                                                                                                   

                             






                                                         

































































































                                                                                                  
//! HTTP handlers for chain CRUD operations.
//!
//! Chains are DAGs (directed acyclic graphs) of contracts for multi-contract orchestration.

use axum::{
    extract::{Path, Query, State},
    http::StatusCode,
    response::IntoResponse,
    Json,
};
use serde::Deserialize;
use utoipa::ToSchema;
use uuid::Uuid;

use crate::db::models::{
    AddContractDefinitionRequest, ChainContractDefinition, ChainContractDetail,
    ChainDefinitionGraphResponse, ChainEditorData, ChainEvent, ChainGraphResponse, ChainSummary,
    ChainWithContracts, CreateChainRequest, CreateTaskRequest, StartChainRequest,
    StartChainResponse, UpdateChainRequest, UpdateContractDefinitionRequest,
};
use crate::db::repository::{self, RepositoryError};
use crate::server::auth::Authenticated;
use crate::server::messages::ApiError;
use crate::server::state::SharedState;

// =============================================================================
// Query Parameters
// =============================================================================

/// Query parameters for listing chains.
#[derive(Debug, Deserialize, ToSchema)]
pub struct ListChainsQuery {
    /// Filter by status (active, completed, archived)
    pub status: Option<String>,
    /// Maximum number of results
    #[serde(default = "default_limit")]
    pub limit: i32,
    /// Offset for pagination
    #[serde(default)]
    pub offset: i32,
}

fn default_limit() -> i32 {
    50
}

// =============================================================================
// Response Types
// =============================================================================

/// Response for listing chains.
#[derive(Debug, serde::Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ChainListResponse {
    pub chains: Vec<ChainSummary>,
    pub total: i64,
}

// =============================================================================
// Handlers
// =============================================================================

/// List chains for the authenticated user.
///
/// GET /api/v1/chains
#[utoipa::path(
    get,
    path = "/api/v1/chains",
    responses(
        (status = 200, description = "List of chains", body = ChainListResponse),
        (status = 401, description = "Unauthorized", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
        (status = 500, description = "Internal server error", body = ApiError)
    ),
    security(
        ("bearer_auth" = []),
        ("api_key" = [])
    ),
    tag = "Chains"
)]
pub async fn list_chains(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Query(query): Query<ListChainsQuery>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    match repository::list_chains_for_owner(pool, auth.owner_id).await {
        Ok(mut chains) => {
            // Apply filters
            if let Some(status) = &query.status {
                chains.retain(|c| c.status == *status);
            }
            // Apply pagination
            let total = chains.len() as i64;
            let chains: Vec<_> = chains
                .into_iter()
                .skip(query.offset as usize)
                .take(query.limit as usize)
                .collect();
            Json(ChainListResponse { chains, total }).into_response()
        }
        Err(e) => {
            tracing::error!("Failed to list chains: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response()
        }
    }
}

/// Create a new chain with contracts.
///
/// POST /api/v1/chains
#[utoipa::path(
    post,
    path = "/api/v1/chains",
    request_body = CreateChainRequest,
    responses(
        (status = 201, description = "Chain created"),
        (status = 400, description = "Invalid request", body = ApiError),
        (status = 401, description = "Unauthorized", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
        (status = 500, description = "Internal server error", body = ApiError)
    ),
    security(
        ("bearer_auth" = []),
        ("api_key" = [])
    ),
    tag = "Chains"
)]
pub async fn create_chain(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Json(req): Json<CreateChainRequest>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    // Validate the request
    if req.name.trim().is_empty() {
        return (
            StatusCode::BAD_REQUEST,
            Json(ApiError::new("VALIDATION_ERROR", "Chain name cannot be empty")),
        )
            .into_response();
    }

    match repository::create_chain_for_owner(pool, auth.owner_id, req).await {
        Ok(chain) => (StatusCode::CREATED, Json(chain)).into_response(),
        Err(e) => {
            tracing::error!("Failed to create chain: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response()
        }
    }
}

/// Get a chain by ID.
///
/// GET /api/v1/chains/{id}
#[utoipa::path(
    get,
    path = "/api/v1/chains/{id}",
    params(
        ("id" = Uuid, Path, description = "Chain ID")
    ),
    responses(
        (status = 200, description = "Chain with contracts", body = ChainWithContracts),
        (status = 401, description = "Unauthorized", body = ApiError),
        (status = 404, description = "Chain not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
        (status = 500, description = "Internal server error", body = ApiError)
    ),
    security(
        ("bearer_auth" = []),
        ("api_key" = [])
    ),
    tag = "Chains"
)]
pub async fn get_chain(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(chain_id): Path<Uuid>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    match repository::get_chain_with_contracts(pool, chain_id, auth.owner_id).await {
        Ok(Some(chain)) => Json(chain).into_response(),
        Ok(None) => (
            StatusCode::NOT_FOUND,
            Json(ApiError::new("NOT_FOUND", "Chain not found")),
        )
            .into_response(),
        Err(e) => {
            tracing::error!("Failed to get chain: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response()
        }
    }
}

/// Update a chain.
///
/// PUT /api/v1/chains/{id}
#[utoipa::path(
    put,
    path = "/api/v1/chains/{id}",
    params(
        ("id" = Uuid, Path, description = "Chain ID")
    ),
    request_body = UpdateChainRequest,
    responses(
        (status = 200, description = "Chain updated"),
        (status = 400, description = "Invalid request", body = ApiError),
        (status = 401, description = "Unauthorized", body = ApiError),
        (status = 404, description = "Chain not found", body = ApiError),
        (status = 409, description = "Version conflict", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
        (status = 500, description = "Internal server error", body = ApiError)
    ),
    security(
        ("bearer_auth" = []),
        ("api_key" = [])
    ),
    tag = "Chains"
)]
pub async fn update_chain(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(chain_id): Path<Uuid>,
    Json(req): Json<UpdateChainRequest>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    match repository::update_chain_for_owner(pool, chain_id, auth.owner_id, req).await {
        Ok(chain) => Json(chain).into_response(),
        Err(RepositoryError::VersionConflict { expected, actual }) => (
            StatusCode::CONFLICT,
            Json(ApiError::new(
                "VERSION_CONFLICT",
                format!("Version conflict: expected {}, found {}", expected, actual),
            )),
        )
            .into_response(),
        Err(RepositoryError::Database(e)) => {
            // Check if it's a "row not found" error
            let error_str = e.to_string();
            if error_str.contains("no rows") || error_str.contains("RowNotFound") {
                (
                    StatusCode::NOT_FOUND,
                    Json(ApiError::new("NOT_FOUND", "Chain not found")),
                )
                    .into_response()
            } else {
                tracing::error!("Failed to update chain: {}", e);
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(ApiError::new("DB_ERROR", e.to_string())),
                )
                    .into_response()
            }
        }
    }
}

/// Delete (archive) a chain.
///
/// DELETE /api/v1/chains/{id}
#[utoipa::path(
    delete,
    path = "/api/v1/chains/{id}",
    params(
        ("id" = Uuid, Path, description = "Chain ID")
    ),
    responses(
        (status = 200, description = "Chain archived"),
        (status = 401, description = "Unauthorized", body = ApiError),
        (status = 404, description = "Chain not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
        (status = 500, description = "Internal server error", body = ApiError)
    ),
    security(
        ("bearer_auth" = []),
        ("api_key" = [])
    ),
    tag = "Chains"
)]
pub async fn delete_chain(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(chain_id): Path<Uuid>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    match repository::delete_chain_for_owner(pool, chain_id, auth.owner_id).await {
        Ok(true) => Json(serde_json::json!({"archived": true})).into_response(),
        Ok(false) => (
            StatusCode::NOT_FOUND,
            Json(ApiError::new("NOT_FOUND", "Chain not found")),
        )
            .into_response(),
        Err(e) => {
            tracing::error!("Failed to delete chain: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response()
        }
    }
}

/// Get contracts in a chain.
///
/// GET /api/v1/chains/{id}/contracts
#[utoipa::path(
    get,
    path = "/api/v1/chains/{id}/contracts",
    params(
        ("id" = Uuid, Path, description = "Chain ID")
    ),
    responses(
        (status = 200, description = "List of contracts in chain", body = Vec<ChainContractDetail>),
        (status = 401, description = "Unauthorized", body = ApiError),
        (status = 404, description = "Chain not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
        (status = 500, description = "Internal server error", body = ApiError)
    ),
    security(
        ("bearer_auth" = []),
        ("api_key" = [])
    ),
    tag = "Chains"
)]
pub async fn get_chain_contracts(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(chain_id): Path<Uuid>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    // Verify ownership
    match repository::get_chain_for_owner(pool, chain_id, auth.owner_id).await {
        Ok(Some(_)) => {}
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(ApiError::new("NOT_FOUND", "Chain not found")),
            )
                .into_response();
        }
        Err(e) => {
            tracing::error!("Failed to verify chain ownership: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response();
        }
    }

    match repository::list_chain_contracts(pool, chain_id).await {
        Ok(contracts) => Json(contracts).into_response(),
        Err(e) => {
            tracing::error!("Failed to list chain contracts: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response()
        }
    }
}

/// Get chain DAG structure for visualization.
///
/// GET /api/v1/chains/{id}/graph
#[utoipa::path(
    get,
    path = "/api/v1/chains/{id}/graph",
    params(
        ("id" = Uuid, Path, description = "Chain ID")
    ),
    responses(
        (status = 200, description = "Chain graph structure", body = ChainGraphResponse),
        (status = 401, description = "Unauthorized", body = ApiError),
        (status = 404, description = "Chain not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
        (status = 500, description = "Internal server error", body = ApiError)
    ),
    security(
        ("bearer_auth" = []),
        ("api_key" = [])
    ),
    tag = "Chains"
)]
pub async fn get_chain_graph(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(chain_id): Path<Uuid>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    // Verify ownership first
    match repository::get_chain_for_owner(pool, chain_id, auth.owner_id).await {
        Ok(Some(_)) => {}
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(ApiError::new("NOT_FOUND", "Chain not found")),
            )
                .into_response();
        }
        Err(e) => {
            tracing::error!("Failed to verify chain ownership: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response();
        }
    }

    match repository::get_chain_graph(pool, chain_id).await {
        Ok(Some(graph)) => Json(graph).into_response(),
        Ok(None) => (
            StatusCode::NOT_FOUND,
            Json(ApiError::new("NOT_FOUND", "Chain not found")),
        )
            .into_response(),
        Err(e) => {
            tracing::error!("Failed to get chain graph: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response()
        }
    }
}

/// Get chain events.
///
/// GET /api/v1/chains/{id}/events
#[utoipa::path(
    get,
    path = "/api/v1/chains/{id}/events",
    params(
        ("id" = Uuid, Path, description = "Chain ID")
    ),
    responses(
        (status = 200, description = "Chain events", body = Vec<ChainEvent>),
        (status = 401, description = "Unauthorized", body = ApiError),
        (status = 404, description = "Chain not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
        (status = 500, description = "Internal server error", body = ApiError)
    ),
    security(
        ("bearer_auth" = []),
        ("api_key" = [])
    ),
    tag = "Chains"
)]
pub async fn get_chain_events(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(chain_id): Path<Uuid>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    // Verify ownership
    match repository::get_chain_for_owner(pool, chain_id, auth.owner_id).await {
        Ok(Some(_)) => {}
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(ApiError::new("NOT_FOUND", "Chain not found")),
            )
                .into_response();
        }
        Err(e) => {
            tracing::error!("Failed to verify chain ownership: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response();
        }
    }

    match repository::list_chain_events(pool, chain_id).await {
        Ok(events) => Json(events).into_response(),
        Err(e) => {
            tracing::error!("Failed to list chain events: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response()
        }
    }
}

/// Get chain editor data.
///
/// GET /api/v1/chains/{id}/editor
#[utoipa::path(
    get,
    path = "/api/v1/chains/{id}/editor",
    params(
        ("id" = Uuid, Path, description = "Chain ID")
    ),
    responses(
        (status = 200, description = "Chain editor data", body = ChainEditorData),
        (status = 401, description = "Unauthorized", body = ApiError),
        (status = 404, description = "Chain not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
        (status = 500, description = "Internal server error", body = ApiError)
    ),
    security(
        ("bearer_auth" = []),
        ("api_key" = [])
    ),
    tag = "Chains"
)]
pub async fn get_chain_editor(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(chain_id): Path<Uuid>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    match repository::get_chain_editor_data(pool, chain_id, auth.owner_id).await {
        Ok(Some(editor_data)) => Json(editor_data).into_response(),
        Ok(None) => (
            StatusCode::NOT_FOUND,
            Json(ApiError::new("NOT_FOUND", "Chain not found")),
        )
            .into_response(),
        Err(e) => {
            tracing::error!("Failed to get chain editor data: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response()
        }
    }
}

// =============================================================================
// Contract Definition Handlers
// =============================================================================

/// List contract definitions for a chain.
///
/// GET /api/v1/chains/{id}/definitions
#[utoipa::path(
    get,
    path = "/api/v1/chains/{id}/definitions",
    params(
        ("id" = Uuid, Path, description = "Chain ID")
    ),
    responses(
        (status = 200, description = "List of contract definitions", body = Vec<ChainContractDefinition>),
        (status = 401, description = "Unauthorized", body = ApiError),
        (status = 404, description = "Chain not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
        (status = 500, description = "Internal server error", body = ApiError)
    ),
    security(
        ("bearer_auth" = []),
        ("api_key" = [])
    ),
    tag = "Chains"
)]
pub async fn list_chain_definitions(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(chain_id): Path<Uuid>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    // Verify ownership
    match repository::get_chain_for_owner(pool, chain_id, auth.owner_id).await {
        Ok(Some(_)) => {}
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(ApiError::new("NOT_FOUND", "Chain not found")),
            )
                .into_response();
        }
        Err(e) => {
            tracing::error!("Failed to verify chain ownership: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response();
        }
    }

    match repository::list_chain_contract_definitions(pool, chain_id).await {
        Ok(definitions) => Json(definitions).into_response(),
        Err(e) => {
            tracing::error!("Failed to list chain definitions: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response()
        }
    }
}

/// Create a contract definition for a chain.
///
/// POST /api/v1/chains/{id}/definitions
#[utoipa::path(
    post,
    path = "/api/v1/chains/{id}/definitions",
    params(
        ("id" = Uuid, Path, description = "Chain ID")
    ),
    request_body = AddContractDefinitionRequest,
    responses(
        (status = 201, description = "Contract definition created", body = ChainContractDefinition),
        (status = 400, description = "Invalid request", body = ApiError),
        (status = 401, description = "Unauthorized", body = ApiError),
        (status = 404, description = "Chain not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
        (status = 500, description = "Internal server error", body = ApiError)
    ),
    security(
        ("bearer_auth" = []),
        ("api_key" = [])
    ),
    tag = "Chains"
)]
pub async fn create_chain_definition(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(chain_id): Path<Uuid>,
    Json(req): Json<AddContractDefinitionRequest>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    // Validate the request
    if req.name.trim().is_empty() {
        return (
            StatusCode::BAD_REQUEST,
            Json(ApiError::new("VALIDATION_ERROR", "Definition name cannot be empty")),
        )
            .into_response();
    }

    // Verify ownership
    match repository::get_chain_for_owner(pool, chain_id, auth.owner_id).await {
        Ok(Some(_)) => {}
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(ApiError::new("NOT_FOUND", "Chain not found")),
            )
                .into_response();
        }
        Err(e) => {
            tracing::error!("Failed to verify chain ownership: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response();
        }
    }

    match repository::create_chain_contract_definition(pool, chain_id, req).await {
        Ok(definition) => (StatusCode::CREATED, Json(definition)).into_response(),
        Err(e) => {
            tracing::error!("Failed to create chain definition: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response()
        }
    }
}

/// Update a contract definition.
///
/// PUT /api/v1/chains/{chain_id}/definitions/{definition_id}
#[utoipa::path(
    put,
    path = "/api/v1/chains/{chain_id}/definitions/{definition_id}",
    params(
        ("chain_id" = Uuid, Path, description = "Chain ID"),
        ("definition_id" = Uuid, Path, description = "Definition ID")
    ),
    request_body = UpdateContractDefinitionRequest,
    responses(
        (status = 200, description = "Contract definition updated", body = ChainContractDefinition),
        (status = 400, description = "Invalid request", body = ApiError),
        (status = 401, description = "Unauthorized", body = ApiError),
        (status = 404, description = "Chain or definition not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
        (status = 500, description = "Internal server error", body = ApiError)
    ),
    security(
        ("bearer_auth" = []),
        ("api_key" = [])
    ),
    tag = "Chains"
)]
pub async fn update_chain_definition(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path((chain_id, definition_id)): Path<(Uuid, Uuid)>,
    Json(req): Json<UpdateContractDefinitionRequest>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    // Verify ownership
    match repository::get_chain_for_owner(pool, chain_id, auth.owner_id).await {
        Ok(Some(_)) => {}
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(ApiError::new("NOT_FOUND", "Chain not found")),
            )
                .into_response();
        }
        Err(e) => {
            tracing::error!("Failed to verify chain ownership: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response();
        }
    }

    // Verify definition belongs to this chain
    match repository::get_chain_contract_definition(pool, definition_id).await {
        Ok(Some(def)) if def.chain_id == chain_id => {}
        Ok(Some(_)) => {
            return (
                StatusCode::NOT_FOUND,
                Json(ApiError::new("NOT_FOUND", "Definition not found in this chain")),
            )
                .into_response();
        }
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(ApiError::new("NOT_FOUND", "Definition not found")),
            )
                .into_response();
        }
        Err(e) => {
            tracing::error!("Failed to get chain definition: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response();
        }
    }

    match repository::update_chain_contract_definition(pool, definition_id, req).await {
        Ok(definition) => Json(definition).into_response(),
        Err(e) => {
            tracing::error!("Failed to update chain definition: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response()
        }
    }
}

/// Delete a contract definition.
///
/// DELETE /api/v1/chains/{chain_id}/definitions/{definition_id}
#[utoipa::path(
    delete,
    path = "/api/v1/chains/{chain_id}/definitions/{definition_id}",
    params(
        ("chain_id" = Uuid, Path, description = "Chain ID"),
        ("definition_id" = Uuid, Path, description = "Definition ID")
    ),
    responses(
        (status = 200, description = "Contract definition deleted"),
        (status = 401, description = "Unauthorized", body = ApiError),
        (status = 404, description = "Chain or definition not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
        (status = 500, description = "Internal server error", body = ApiError)
    ),
    security(
        ("bearer_auth" = []),
        ("api_key" = [])
    ),
    tag = "Chains"
)]
pub async fn delete_chain_definition(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path((chain_id, definition_id)): Path<(Uuid, Uuid)>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    // Verify ownership
    match repository::get_chain_for_owner(pool, chain_id, auth.owner_id).await {
        Ok(Some(_)) => {}
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(ApiError::new("NOT_FOUND", "Chain not found")),
            )
                .into_response();
        }
        Err(e) => {
            tracing::error!("Failed to verify chain ownership: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response();
        }
    }

    // Verify definition belongs to this chain before deleting
    match repository::get_chain_contract_definition(pool, definition_id).await {
        Ok(Some(def)) if def.chain_id == chain_id => {}
        Ok(Some(_)) => {
            return (
                StatusCode::NOT_FOUND,
                Json(ApiError::new("NOT_FOUND", "Definition not found in this chain")),
            )
                .into_response();
        }
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(ApiError::new("NOT_FOUND", "Definition not found")),
            )
                .into_response();
        }
        Err(e) => {
            tracing::error!("Failed to get chain definition: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response();
        }
    }

    match repository::delete_chain_contract_definition(pool, definition_id).await {
        Ok(true) => Json(serde_json::json!({"deleted": true})).into_response(),
        Ok(false) => (
            StatusCode::NOT_FOUND,
            Json(ApiError::new("NOT_FOUND", "Definition not found")),
        )
            .into_response(),
        Err(e) => {
            tracing::error!("Failed to delete chain definition: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response()
        }
    }
}

/// Get definition graph for a chain (shows definitions + instantiation status).
///
/// GET /api/v1/chains/{id}/definitions/graph
#[utoipa::path(
    get,
    path = "/api/v1/chains/{id}/definitions/graph",
    params(
        ("id" = Uuid, Path, description = "Chain ID")
    ),
    responses(
        (status = 200, description = "Definition graph structure", body = ChainDefinitionGraphResponse),
        (status = 401, description = "Unauthorized", body = ApiError),
        (status = 404, description = "Chain not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
        (status = 500, description = "Internal server error", body = ApiError)
    ),
    security(
        ("bearer_auth" = []),
        ("api_key" = [])
    ),
    tag = "Chains"
)]
pub async fn get_chain_definition_graph(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(chain_id): Path<Uuid>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    // Verify ownership first
    match repository::get_chain_for_owner(pool, chain_id, auth.owner_id).await {
        Ok(Some(_)) => {}
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(ApiError::new("NOT_FOUND", "Chain not found")),
            )
                .into_response();
        }
        Err(e) => {
            tracing::error!("Failed to verify chain ownership: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response();
        }
    }

    match repository::get_chain_definition_graph(pool, chain_id).await {
        Ok(Some(graph)) => Json(graph).into_response(),
        Ok(None) => (
            StatusCode::NOT_FOUND,
            Json(ApiError::new("NOT_FOUND", "Chain not found")),
        )
            .into_response(),
        Err(e) => {
            tracing::error!("Failed to get chain definition graph: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response()
        }
    }
}

// =============================================================================
// Chain Control Handlers
// =============================================================================

/// Start a chain (spawns supervisor and creates root contracts).
///
/// POST /api/v1/chains/{id}/start
#[utoipa::path(
    post,
    path = "/api/v1/chains/{id}/start",
    params(
        ("id" = Uuid, Path, description = "Chain ID")
    ),
    request_body(content = Option<StartChainRequest>, description = "Optional start options"),
    responses(
        (status = 200, description = "Chain started", body = StartChainResponse),
        (status = 400, description = "Chain cannot be started", body = ApiError),
        (status = 401, description = "Unauthorized", body = ApiError),
        (status = 404, description = "Chain not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
        (status = 500, description = "Internal server error", body = ApiError)
    ),
    security(
        ("bearer_auth" = []),
        ("api_key" = [])
    ),
    tag = "Chains"
)]
pub async fn start_chain(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(chain_id): Path<Uuid>,
    body: Option<Json<StartChainRequest>>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    let req = body.map(|b| b.0).unwrap_or(StartChainRequest {
        with_supervisor: false,
        repository_url: None,
    });

    // Verify ownership and get chain
    let chain = match repository::get_chain_for_owner(pool, chain_id, auth.owner_id).await {
        Ok(Some(c)) => c,
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(ApiError::new("NOT_FOUND", "Chain not found")),
            )
                .into_response();
        }
        Err(e) => {
            tracing::error!("Failed to get chain: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response();
        }
    };

    // Check if chain can be started
    if chain.status == "active" {
        return (
            StatusCode::BAD_REQUEST,
            Json(ApiError::new("ALREADY_ACTIVE", "Chain is already active")),
        )
            .into_response();
    }
    if chain.status == "completed" {
        return (
            StatusCode::BAD_REQUEST,
            Json(ApiError::new("ALREADY_COMPLETED", "Chain is already completed")),
        )
            .into_response();
    }

    // Get definitions to check if there are any
    let definitions = match repository::list_chain_contract_definitions(pool, chain_id).await {
        Ok(d) => d,
        Err(e) => {
            tracing::error!("Failed to list chain definitions: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response();
        }
    };

    if definitions.is_empty() {
        return (
            StatusCode::BAD_REQUEST,
            Json(ApiError::new("NO_DEFINITIONS", "Chain has no contract definitions")),
        )
            .into_response();
    }

    // Update chain status to active
    match repository::update_chain_status(pool, chain_id, "active").await {
        Ok(_) => {}
        Err(e) => {
            tracing::error!("Failed to update chain status: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response();
        }
    }

    // Create supervisor task if requested
    let mut supervisor_task_id: Option<Uuid> = None;
    if req.with_supervisor {
        let supervisor_name = format!("Chain Supervisor: {}", chain.name);
        let supervisor_plan = format!(
            r#"You are the supervisor for chain "{}".

## Environment Variables
- MAKIMA_CHAIN_ID={}
- MAKIMA_API_URL (configured)
- MAKIMA_API_KEY (configured)

## Your Responsibilities
1. Monitor chain progress by periodically checking chain status
2. Validate that contracts are completing successfully
3. Identify and report any issues or blockers
4. Track the overall chain progress through the DAG

## Available Commands
Use these makima CLI commands to monitor the chain:

```bash
# Check chain status
makima chain status {}

# List contracts in the chain
makima chain contracts {}

# View the chain DAG with current status
makima chain graph {} --with-status
```

## Monitoring Loop
1. Check chain status every few minutes
2. If a contract fails, investigate the issue
3. Report progress to the user when milestones are reached
4. Mark the chain as complete when all contracts finish

## Current Chain Info
- Chain ID: {}
- Chain Name: {}
- Total definitions: {}

Begin monitoring the chain. Check the initial status and report what you find."#,
            chain.name,
            chain_id,
            chain_id,
            chain_id,
            chain_id,
            chain_id,
            chain.name,
            definitions.len()
        );

        let supervisor_req = CreateTaskRequest {
            name: supervisor_name,
            description: Some(format!("Supervisor task for chain: {}", chain.name)),
            plan: supervisor_plan,
            repository_url: req.repository_url.clone(),
            base_branch: None,
            target_branch: None,
            parent_task_id: None,
            contract_id: None, // Chain supervisor is not tied to a specific contract
            target_repo_path: None,
            completion_action: None,
            continue_from_task_id: None,
            copy_files: None,
            is_supervisor: true,
            checkpoint_sha: None,
            priority: 0,
            merge_mode: None,
            branched_from_task_id: None,
            conversation_history: None,
            supervisor_worktree_task_id: None,
        };

        match repository::create_task_for_owner(pool, auth.owner_id, supervisor_req).await {
            Ok(supervisor_task) => {
                tracing::info!(
                    chain_id = %chain_id,
                    supervisor_task_id = %supervisor_task.id,
                    "Created supervisor task for chain"
                );

                // Update chain with supervisor_task_id
                if let Err(e) =
                    repository::set_chain_supervisor_task(pool, chain_id, Some(supervisor_task.id))
                        .await
                {
                    tracing::warn!(
                        chain_id = %chain_id,
                        error = %e,
                        "Failed to link supervisor task to chain"
                    );
                }

                supervisor_task_id = Some(supervisor_task.id);
            }
            Err(e) => {
                tracing::warn!(
                    chain_id = %chain_id,
                    error = %e,
                    "Failed to create supervisor task for chain"
                );
            }
        }
    }

    // Progress the chain - this creates root contracts (definitions with no dependencies)
    let progression = match repository::progress_chain(pool, chain_id, auth.owner_id).await {
        Ok(p) => p,
        Err(e) => {
            tracing::error!("Failed to progress chain: {}", e);
            // Chain is active but no contracts created - return partial success
            return Json(StartChainResponse {
                chain_id,
                supervisor_task_id,
                contracts_created: vec![],
                status: "active".to_string(),
            })
            .into_response();
        }
    };

    Json(StartChainResponse {
        chain_id,
        supervisor_task_id,
        contracts_created: progression.contracts_created,
        status: if progression.chain_completed {
            "completed".to_string()
        } else {
            "active".to_string()
        },
    })
    .into_response()
}

/// Stop a chain (kills supervisor, marks as archived).
///
/// POST /api/v1/chains/{id}/stop
#[utoipa::path(
    post,
    path = "/api/v1/chains/{id}/stop",
    params(
        ("id" = Uuid, Path, description = "Chain ID")
    ),
    responses(
        (status = 200, description = "Chain stopped"),
        (status = 400, description = "Chain cannot be stopped", body = ApiError),
        (status = 401, description = "Unauthorized", body = ApiError),
        (status = 404, description = "Chain not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
        (status = 500, description = "Internal server error", body = ApiError)
    ),
    security(
        ("bearer_auth" = []),
        ("api_key" = [])
    ),
    tag = "Chains"
)]
pub async fn stop_chain(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(chain_id): Path<Uuid>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    // Verify ownership and get chain
    let chain = match repository::get_chain_for_owner(pool, chain_id, auth.owner_id).await {
        Ok(Some(c)) => c,
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(ApiError::new("NOT_FOUND", "Chain not found")),
            )
                .into_response();
        }
        Err(e) => {
            tracing::error!("Failed to get chain: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response();
        }
    };

    // Check if chain can be stopped
    if chain.status != "active" {
        return (
            StatusCode::BAD_REQUEST,
            Json(ApiError::new(
                "NOT_ACTIVE",
                format!("Chain is not active (status: {})", chain.status),
            )),
        )
            .into_response();
    }

    // TODO: Kill the supervisor task if running
    // Clear supervisor task ID and set status to archived
    match repository::set_chain_supervisor_task(pool, chain_id, None).await {
        Ok(_) => {}
        Err(e) => {
            tracing::error!("Failed to clear chain supervisor: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response();
        }
    }

    match repository::update_chain_status(pool, chain_id, "archived").await {
        Ok(_) => Json(serde_json::json!({"stopped": true, "status": "archived"})).into_response(),
        Err(e) => {
            tracing::error!("Failed to update chain status: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response()
        }
    }
}