mockforge-registry-server 0.3.128

Plugin registry server for MockForge
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
//! Scenario marketplace handlers
//!
//! Provides endpoints for the scenario marketplace (data scenarios for mock systems)

use axum::{
    extract::{Path, State},
    http::HeaderMap,
    Json,
};
use base64::Engine;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::{
    error::{ApiError, ApiResult},
    middleware::{resolve_org_context, AuthUser, OptionalAuthUser},
    models::{AuditEventType, FeatureType, ScenarioReview, ScenarioVersion, UsageCounter, User},
    AppState,
};

/// Search scenarios
/// Supports org filtering: if user is authenticated, includes their org's private scenarios
pub async fn search_scenarios(
    State(state): State<AppState>,
    OptionalAuthUser(maybe_user_id): OptionalAuthUser,
    headers: HeaderMap,
    Json(query): Json<ScenarioSearchQuery>,
) -> ApiResult<Json<ScenarioSearchResults>> {
    let metrics = crate::metrics::MarketplaceMetrics::start(state.metrics.clone(), "scenario");
    let pool = state.db.pool();

    // Try to resolve org context for filtering (optional)
    // If user is authenticated, include their org's private scenarios
    let org_id = if let Some(user_id) = maybe_user_id {
        if let Ok(org_ctx) = resolve_org_context(&state, user_id, &headers, None).await {
            Some(org_ctx.org_id)
        } else {
            None
        }
    } else {
        None
    };

    // Validate and limit pagination parameters
    let per_page = query.per_page.clamp(1, 100); // Max 100 items per page
    let page = query.page;
    let limit = per_page as i64;
    let offset = (page * per_page) as i64;

    // Map sort order
    let sort = match query.sort {
        ScenarioSortOrder::Relevance => "downloads", // Default to downloads for relevance
        ScenarioSortOrder::Downloads => "downloads",
        ScenarioSortOrder::Rating => "rating",
        ScenarioSortOrder::Recent => "recent",
        ScenarioSortOrder::Name => "name",
    };

    // Get total count for pagination (before fetching results)
    let total = state
        .store
        .count_search_scenarios(
            query.query.as_deref(),
            query.category.as_deref(),
            &query.tags,
            org_id,
        )
        .await? as usize;

    // Search scenarios
    let scenarios = state
        .store
        .search_scenarios(
            query.query.as_deref(),
            query.category.as_deref(),
            &query.tags,
            org_id,
            sort,
            limit,
            offset,
        )
        .await?;

    // Batch-fetch star counts for the whole page in one query (avoids N+1).
    let scenario_ids: Vec<Uuid> = scenarios.iter().map(|s| s.id).collect();
    let star_counts = state.store.count_scenario_stars_batch(&scenario_ids).await?;

    // Convert to registry entries
    let mut entries = Vec::new();
    for scenario in scenarios {
        let versions = ScenarioVersion::get_by_scenario(pool, scenario.id)
            .await
            .map_err(ApiError::Database)?;

        let author = User::find_by_id(pool, scenario.author_id)
            .await
            .map_err(ApiError::Database)?
            .unwrap_or_else(|| User::placeholder(scenario.author_id));

        let version_entries: Vec<ScenarioVersionEntry> = versions
            .into_iter()
            .filter(|v| !v.yanked)
            .map(|v| ScenarioVersionEntry {
                version: v.version,
                download_url: v.download_url,
                checksum: v.checksum,
                size: v.file_size as u64,
                published_at: v.published_at.to_rfc3339(),
                yanked: v.yanked,
                min_mockforge_version: v.min_mockforge_version,
            })
            .collect();

        // Load top 3 reviews (most helpful) for search results
        let reviews = ScenarioReview::get_by_scenario(pool, scenario.id, 3, 0)
            .await
            .map_err(ApiError::Database)?;

        // Batch load all reviewers to avoid N+1 queries
        let reviewer_ids: Vec<Uuid> = reviews.iter().map(|r| r.reviewer_id).collect();
        let reviewers: std::collections::HashMap<Uuid, User> = if !reviewer_ids.is_empty() {
            User::find_by_ids(pool, &reviewer_ids)
                .await
                .map_err(ApiError::Database)?
                .into_iter()
                .map(|u| (u.id, u))
                .collect()
        } else {
            std::collections::HashMap::new()
        };

        let review_responses: Vec<ScenarioReviewResponse> = reviews
            .into_iter()
            .map(|review| {
                let reviewer = reviewers
                    .get(&review.reviewer_id)
                    .cloned()
                    .unwrap_or_else(|| User::placeholder(review.reviewer_id));

                ScenarioReviewResponse {
                    id: review.id.to_string(),
                    reviewer: reviewer.username,
                    reviewer_email: Some(reviewer.email),
                    rating: review.rating as u8,
                    title: review.title,
                    comment: review.comment,
                    created_at: review.created_at.to_rfc3339(),
                    helpful_count: review.helpful_count as u32,
                    verified_purchase: review.verified_purchase,
                }
            })
            .collect();

        let stars = star_counts.get(&scenario.id).copied().unwrap_or(0) as u64;

        entries.push(ScenarioRegistryEntry {
            name: scenario.name,
            description: scenario.description,
            version: scenario.current_version,
            versions: version_entries,
            author: author.username,
            author_id: author.id.to_string(),
            author_email: Some(author.email),
            tags: scenario.tags,
            category: scenario.category,
            downloads: scenario.downloads_total as u64,
            rating: scenario.rating_avg.to_string().parse::<f64>().unwrap_or(0.0),
            reviews_count: scenario.rating_count as u32,
            stars,
            reviews: review_responses,
            repository: scenario.repository,
            homepage: scenario.homepage,
            license: scenario.license,
            created_at: scenario.created_at.to_rfc3339(),
            updated_at: scenario.updated_at.to_rfc3339(),
        });
    }

    // Record metrics
    metrics.record_search_success();

    Ok(Json(ScenarioSearchResults {
        scenarios: entries,
        total,
        page,
        per_page,
    }))
}

/// Get scenario by name
pub async fn get_scenario(
    State(state): State<AppState>,
    Path(name): Path<String>,
) -> ApiResult<Json<ScenarioRegistryEntry>> {
    let metrics = crate::metrics::MarketplaceMetrics::start(state.metrics.clone(), "scenario");
    let pool = state.db.pool();

    let scenario = state
        .store
        .find_scenario_by_name(&name)
        .await?
        .ok_or_else(|| ApiError::ScenarioNotFound(name.clone()))?;

    let versions = ScenarioVersion::get_by_scenario(pool, scenario.id)
        .await
        .map_err(ApiError::Database)?;

    let author = state
        .store
        .find_user_by_id(scenario.author_id)
        .await?
        .unwrap_or_else(|| User::placeholder(scenario.author_id));

    let version_entries: Vec<ScenarioVersionEntry> = versions
        .into_iter()
        .map(|v| ScenarioVersionEntry {
            version: v.version,
            download_url: v.download_url,
            checksum: v.checksum,
            size: v.file_size as u64,
            published_at: v.published_at.to_rfc3339(),
            yanked: v.yanked,
            min_mockforge_version: v.min_mockforge_version,
        })
        .collect();

    // Load top 5 reviews (most helpful) for single scenario view
    let reviews = ScenarioReview::get_by_scenario(pool, scenario.id, 5, 0)
        .await
        .map_err(ApiError::Database)?;

    // Batch load all reviewers to avoid N+1 queries
    let reviewer_ids: Vec<Uuid> = reviews.iter().map(|r| r.reviewer_id).collect();
    let reviewers: std::collections::HashMap<Uuid, User> = if !reviewer_ids.is_empty() {
        User::find_by_ids(pool, &reviewer_ids)
            .await
            .map_err(ApiError::Database)?
            .into_iter()
            .map(|u| (u.id, u))
            .collect()
    } else {
        std::collections::HashMap::new()
    };

    let review_responses: Vec<ScenarioReviewResponse> = reviews
        .into_iter()
        .map(|review| {
            let reviewer = reviewers
                .get(&review.reviewer_id)
                .cloned()
                .unwrap_or_else(|| User::placeholder(review.reviewer_id));

            ScenarioReviewResponse {
                id: review.id.to_string(),
                reviewer: reviewer.username,
                reviewer_email: Some(reviewer.email),
                rating: review.rating as u8,
                title: review.title,
                comment: review.comment,
                created_at: review.created_at.to_rfc3339(),
                helpful_count: review.helpful_count as u32,
                verified_purchase: review.verified_purchase,
            }
        })
        .collect();

    let stars = state.store.count_scenario_stars(scenario.id).await? as u64;

    // Record metrics
    metrics.record_download_success();

    Ok(Json(ScenarioRegistryEntry {
        name: scenario.name,
        description: scenario.description,
        version: scenario.current_version,
        versions: version_entries,
        author: author.username,
        author_id: author.id.to_string(),
        author_email: Some(author.email),
        tags: scenario.tags,
        category: scenario.category,
        downloads: scenario.downloads_total as u64,
        rating: scenario.rating_avg.to_string().parse::<f64>().unwrap_or(0.0),
        reviews_count: scenario.rating_count as u32,
        stars,
        reviews: review_responses,
        repository: scenario.repository,
        homepage: scenario.homepage,
        license: scenario.license,
        created_at: scenario.created_at.to_rfc3339(),
        updated_at: scenario.updated_at.to_rfc3339(),
    }))
}

/// Get scenario version
pub async fn get_scenario_version(
    State(state): State<AppState>,
    Path((name, version)): Path<(String, String)>,
) -> ApiResult<Json<ScenarioVersionEntry>> {
    let pool = state.db.pool();

    let scenario = state
        .store
        .find_scenario_by_name(&name)
        .await?
        .ok_or_else(|| ApiError::ScenarioNotFound(name.clone()))?;

    let scenario_version = ScenarioVersion::find(pool, scenario.id, &version)
        .await
        .map_err(ApiError::Database)?
        .ok_or_else(|| ApiError::InvalidVersion(version.clone()))?;

    Ok(Json(ScenarioVersionEntry {
        version: scenario_version.version,
        download_url: scenario_version.download_url,
        checksum: scenario_version.checksum,
        size: scenario_version.file_size as u64,
        published_at: scenario_version.published_at.to_rfc3339(),
        yanked: scenario_version.yanked,
        min_mockforge_version: scenario_version.min_mockforge_version,
    }))
}

/// Publish a scenario
pub async fn publish_scenario(
    State(state): State<AppState>,
    AuthUser(author_id): AuthUser,
    headers: HeaderMap,
    Json(request): Json<PublishScenarioRequest>,
) -> ApiResult<Json<PublishScenarioResponse>> {
    let metrics = crate::metrics::MarketplaceMetrics::start(state.metrics.clone(), "scenario");
    let pool = state.db.pool();

    // Resolve org context
    let org_ctx = resolve_org_context(&state, author_id, &headers, None)
        .await
        .map_err(|_| ApiError::OrganizationNotFound)?;

    // Check publishing limits
    let limits = &org_ctx.org.limits_json;
    let max_scenarios = limits.get("max_scenarios_published").and_then(|v| v.as_i64()).unwrap_or(1);

    if max_scenarios >= 0 {
        let existing = state.store.list_scenarios_by_org(org_ctx.org_id).await?;

        if existing.len() as i64 >= max_scenarios {
            return Err(ApiError::InvalidRequest(format!(
                "Scenario limit exceeded. Your plan allows {} scenarios. Upgrade to publish more.",
                max_scenarios
            )));
        }
    }

    // Check storage limit
    let storage_limit_gb = limits.get("storage_gb").and_then(|v| v.as_i64()).unwrap_or(1);
    let storage_limit_bytes = storage_limit_gb * 1_000_000_000;

    let usage = UsageCounter::get_or_create_current(pool, org_ctx.org_id)
        .await
        .map_err(ApiError::Database)?;

    let new_storage = usage.storage_bytes + request.size as i64;
    if new_storage > storage_limit_bytes {
        return Err(ApiError::InvalidRequest(format!(
            "Storage limit exceeded. Your plan allows {} GB.",
            storage_limit_gb
        )));
    }

    // Validate checksum format
    crate::validation::validate_checksum(&request.checksum)?;

    // Validate base64 encoding
    crate::validation::validate_base64(&request.package)?;

    // Parse manifest
    let manifest: serde_json::Value = serde_json::from_str(&request.manifest)
        .map_err(|e| ApiError::InvalidRequest(format!("Invalid manifest JSON: {}", e)))?;

    // Extract scenario name and version from manifest for validation
    let name = manifest
        .get("name")
        .and_then(|v| v.as_str())
        .ok_or_else(|| ApiError::InvalidRequest("Manifest must contain 'name' field".to_string()))?
        .to_string();

    let version = manifest
        .get("version")
        .and_then(|v| v.as_str())
        .ok_or_else(|| {
            ApiError::InvalidRequest("Manifest must contain 'version' field".to_string())
        })?
        .to_string();

    // Validate name and version
    crate::validation::validate_name(&name)?;
    crate::validation::validate_version(&version)?;

    // Decode package data
    let package_data = base64::engine::general_purpose::STANDARD
        .decode(&request.package)
        .map_err(|e| ApiError::InvalidRequest(format!("Invalid base64: {}", e)))?;

    // Validate package file
    crate::validation::validate_package_file(
        &package_data,
        request.size,
        crate::validation::MAX_SCENARIO_SIZE,
    )?;

    // Verify checksum
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(&package_data);
    let calculated_checksum = hex::encode(hasher.finalize());

    if calculated_checksum != request.checksum {
        return Err(ApiError::InvalidRequest("Checksum mismatch".to_string()));
    }

    // Generate slug from name
    let slug = name
        .as_str()
        .to_lowercase()
        .chars()
        .map(|c| {
            if c.is_alphanumeric() || c == '-' {
                c
            } else {
                '-'
            }
        })
        .collect::<String>()
        .trim_matches('-')
        .replace("--", "-");

    // Upload to storage
    let download_url = state
        .storage
        .upload_scenario(&name, &version, package_data)
        .await
        .map_err(|e| ApiError::Storage(e.to_string()))?;

    // Create or update scenario
    let scenario = if let Some(existing) = state.store.find_scenario_by_name(&name).await? {
        // Update existing scenario
        existing
    } else {
        // Create new scenario
        let category = manifest.get("category").and_then(|v| v.as_str()).unwrap_or("other");
        let description = manifest.get("description").and_then(|v| v.as_str()).unwrap_or("");
        let license = manifest.get("license").and_then(|v| v.as_str()).unwrap_or("MIT");

        state
            .store
            .create_scenario(
                Some(org_ctx.org_id),
                &name,
                &slug,
                description,
                author_id,
                &version,
                category,
                license,
                manifest.clone(),
            )
            .await?
    };

    // Create version entry
    let min_mockforge_version = manifest
        .get("compatibility")
        .and_then(|c| c.get("min_version"))
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    ScenarioVersion::create(
        pool,
        scenario.id,
        &version,
        manifest,
        &download_url,
        &request.checksum,
        request.size as i64,
        min_mockforge_version.as_deref(),
    )
    .await
    .map_err(ApiError::Database)?;

    // Update storage usage
    UsageCounter::update_storage(pool, org_ctx.org_id, new_storage)
        .await
        .map_err(ApiError::Database)?;

    // Track feature usage
    state
        .store
        .record_feature_usage(
            org_ctx.org_id,
            Some(author_id),
            FeatureType::ScenarioPublish,
            Some(serde_json::json!({
                "scenario_name": name,
                "version": version,
            })),
        )
        .await;

    // Record audit event
    let ip_address = headers
        .get("X-Forwarded-For")
        .or_else(|| headers.get("X-Real-IP"))
        .and_then(|h| h.to_str().ok())
        .map(|s| s.split(',').next().unwrap_or(s).trim());
    let user_agent = headers.get("User-Agent").and_then(|h| h.to_str().ok());

    state
        .store
        .record_audit_event(
            org_ctx.org_id,
            Some(author_id),
            AuditEventType::ScenarioPublished,
            format!("Scenario {} version {} published", name, version),
            Some(serde_json::json!({
                "scenario_name": name,
                "version": version,
            })),
            ip_address,
            user_agent,
        )
        .await;

    // Record metrics
    metrics.record_publish_success();

    Ok(Json(PublishScenarioResponse {
        name: name.to_string(),
        version: version.to_string(),
        download_url,
        published_at: chrono::Utc::now().to_rfc3339(),
    }))
}

// Request/Response types (matching scenario registry client)

#[derive(Debug, Deserialize)]
pub struct ScenarioSearchQuery {
    pub query: Option<String>,
    pub category: Option<String>,
    pub tags: Vec<String>,
    #[serde(default)]
    pub sort: ScenarioSortOrder,
    #[serde(default = "default_page")]
    pub page: usize,
    #[serde(default = "default_per_page")]
    pub per_page: usize,
}

fn default_page() -> usize {
    0
}

fn default_per_page() -> usize {
    20
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum ScenarioSortOrder {
    #[default]
    Relevance,
    Downloads,
    Rating,
    Recent,
    Name,
}

#[derive(Debug, Serialize)]
pub struct ScenarioSearchResults {
    pub scenarios: Vec<ScenarioRegistryEntry>,
    pub total: usize,
    pub page: usize,
    pub per_page: usize,
}

#[derive(Debug, Serialize)]
pub struct ScenarioRegistryEntry {
    pub name: String,
    pub description: String,
    pub version: String,
    pub versions: Vec<ScenarioVersionEntry>,
    pub author: String,
    /// Stringified UUID of the scenario's author. The UI compares this
    /// against `useAuthStore.user.id` to decide whether to show the
    /// "Yank version" button on each version row.
    pub author_id: String,
    pub author_email: Option<String>,
    pub tags: Vec<String>,
    pub category: String,
    pub downloads: u64,
    pub rating: f64,
    pub reviews_count: u32,
    /// Live count of `scenario_stars` rows for this scenario.
    pub stars: u64,
    pub reviews: Vec<ScenarioReviewResponse>,
    pub repository: Option<String>,
    pub homepage: Option<String>,
    pub license: String,
    pub created_at: String,
    pub updated_at: String,
}

#[derive(Debug, Serialize)]
pub struct ScenarioVersionEntry {
    pub version: String,
    pub download_url: String,
    pub checksum: String,
    pub size: u64,
    pub published_at: String,
    pub yanked: bool,
    pub min_mockforge_version: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct ScenarioReviewResponse {
    pub id: String,
    pub reviewer: String,
    pub reviewer_email: Option<String>,
    pub rating: u8,
    pub title: Option<String>,
    pub comment: String,
    pub created_at: String,
    pub helpful_count: u32,
    pub verified_purchase: bool,
}

#[derive(Debug, Deserialize)]
pub struct PublishScenarioRequest {
    pub manifest: String, // JSON string
    pub package: String,  // Base64 encoded
    pub checksum: String,
    pub size: u64,
}

#[derive(Debug, Serialize)]
pub struct PublishScenarioResponse {
    pub name: String,
    pub version: String,
    pub download_url: String,
    pub published_at: String,
}

/// Slim scenario entry returned by the org-scoped list / lookup endpoints.
///
/// Excludes marketplace-only fields (rating, downloads, verification) that
/// aren't useful to the federation-activation picker.
#[derive(Debug, Serialize)]
pub struct OrgScenarioEntry {
    pub id: Uuid,
    pub name: String,
    pub slug: String,
    pub description: String,
    pub current_version: String,
    pub category: String,
    pub tags: Vec<String>,
    pub manifest_json: serde_json::Value,
    pub created_at: String,
    pub updated_at: String,
}

impl OrgScenarioEntry {
    fn from_model(s: crate::models::Scenario) -> Self {
        Self {
            id: s.id,
            name: s.name,
            slug: s.slug,
            description: s.description,
            current_version: s.current_version,
            category: s.category,
            tags: s.tags,
            manifest_json: s.manifest_json,
            created_at: s.created_at.to_rfc3339(),
            updated_at: s.updated_at.to_rfc3339(),
        }
    }
}

/// `GET /api/v1/scenarios` — list scenarios belonging to the caller's org.
///
/// Backs the federation "Activate Scenario" picker. Only scenarios whose
/// `org_id` matches the caller's resolved org context are returned; public
/// marketplace scenarios (with `org_id = NULL`) are excluded — use the
/// marketplace search endpoint for those.
pub async fn list_org_scenarios(
    State(state): State<AppState>,
    AuthUser(user_id): AuthUser,
    headers: HeaderMap,
) -> ApiResult<Json<Vec<OrgScenarioEntry>>> {
    let org_ctx = resolve_org_context(&state, user_id, &headers, None)
        .await
        .map_err(|_| ApiError::InvalidRequest("Organization not found".to_string()))?;

    let scenarios = state.store.list_scenarios_by_org(org_ctx.org_id).await?;
    Ok(Json(scenarios.into_iter().map(OrgScenarioEntry::from_model).collect()))
}

/// `GET /api/v1/scenarios/{id}` — fetch one scenario by UUID, org-scoped.
///
/// Returns 400 if the scenario isn't visible to the caller's org (either
/// missing entirely or owned by another org). Marketplace scenarios
/// (`org_id = NULL`) are allowed — they're readable by anyone.
pub async fn get_org_scenario_by_id(
    State(state): State<AppState>,
    AuthUser(user_id): AuthUser,
    headers: HeaderMap,
    Path(id): Path<Uuid>,
) -> ApiResult<Json<OrgScenarioEntry>> {
    let org_ctx = resolve_org_context(&state, user_id, &headers, None)
        .await
        .map_err(|_| ApiError::InvalidRequest("Organization not found".to_string()))?;

    let scenario = state
        .store
        .find_scenario_by_id(id)
        .await?
        .ok_or_else(|| ApiError::InvalidRequest("Scenario not found".to_string()))?;

    match scenario.org_id {
        None => {} // public marketplace scenario; everyone can read
        Some(sid) if sid == org_ctx.org_id => {}
        Some(_) => {
            return Err(ApiError::InvalidRequest(
                "Scenario does not belong to this organization".to_string(),
            ));
        }
    }

    Ok(Json(OrgScenarioEntry::from_model(scenario)))
}

/// Toggle a star for (current user, scenario by name).
/// Returns the new star state and updated count.
pub async fn toggle_scenario_star(
    State(state): State<AppState>,
    AuthUser(user_id): AuthUser,
    Path(name): Path<String>,
) -> ApiResult<Json<ScenarioStarToggleResponse>> {
    let scenario = state
        .store
        .find_scenario_by_name(&name)
        .await?
        .ok_or_else(|| ApiError::ScenarioNotFound(name.clone()))?;

    let (starred, stars) = state.store.toggle_scenario_star(scenario.id, user_id).await?;

    Ok(Json(ScenarioStarToggleResponse { starred, stars }))
}

/// Whether the current user has starred a scenario.
pub async fn get_scenario_star_state(
    State(state): State<AppState>,
    AuthUser(user_id): AuthUser,
    Path(name): Path<String>,
) -> ApiResult<Json<ScenarioStarStateResponse>> {
    let scenario = state
        .store
        .find_scenario_by_name(&name)
        .await?
        .ok_or_else(|| ApiError::ScenarioNotFound(name.clone()))?;

    let starred = state.store.is_scenario_starred_by(scenario.id, user_id).await?;
    let stars = state.store.count_scenario_stars(scenario.id).await?;

    Ok(Json(ScenarioStarStateResponse { starred, stars }))
}

/// Yank a scenario version. The version row stays but is hidden from
/// search/list paths. Only the scenario's author may yank.
pub async fn yank_scenario_version(
    State(state): State<AppState>,
    AuthUser(user_id): AuthUser,
    Path((name, version)): Path<(String, String)>,
) -> ApiResult<Json<serde_json::Value>> {
    let scenario = state
        .store
        .find_scenario_by_name(&name)
        .await?
        .ok_or_else(|| ApiError::ScenarioNotFound(name.clone()))?;

    if scenario.author_id != user_id {
        return Err(ApiError::PermissionDenied);
    }

    let pool = state.db.pool();
    let scenario_version = ScenarioVersion::find(pool, scenario.id, &version)
        .await
        .map_err(ApiError::Database)?
        .ok_or_else(|| ApiError::InvalidVersion(version.clone()))?;

    state.store.yank_scenario_version(scenario_version.id).await?;

    Ok(Json(serde_json::json!({
        "success": true,
        "message": format!("Version {} of {} yanked successfully", version, name)
    })))
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ScenarioStarToggleResponse {
    pub starred: bool,
    pub stars: i64,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ScenarioStarStateResponse {
    pub starred: bool,
    pub stars: i64,
}