heliosdb-nano 3.22.3

PostgreSQL-compatible embedded database with TDE + ZKE encryption, HNSW vector search, Product Quantization, git-like branching, time-travel queries, materialized views, row-level security, and 50+ enterprise features
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
//! Webhook Server for Git Provider Integration
//!
//! Provides HTTP endpoints for receiving webhooks from GitHub, GitLab,
//! and other Git providers to automate PR/MR preview environments.
//!
//! ## Supported Providers
//!
//! - **GitHub**: PR opened/closed/merged events
//! - **GitLab**: MR opened/closed/merged events
//! - **Generic**: Provider-agnostic webhook interface
//!
//! ## PR Lifecycle
//!
//! ```text
//! PR Opened  → create_preview_branch(base, pr_ref)
//! PR Updated → sync + apply_migrations(pr_branch)
//! PR Merged  → merge_db_branch(pr_branch, base) + cleanup
//! PR Closed  → drop_preview_branch(pr_branch)
//! ```

#![allow(dead_code)]
#![allow(unused_variables)]

use crate::storage::BranchId;
use crate::{Error, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Git provider type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum GitProvider {
    GitHub,
    GitLab,
    Bitbucket,
    Generic,
}

impl Default for GitProvider {
    fn default() -> Self {
        GitProvider::Generic
    }
}

/// Webhook event type
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WebhookEventType {
    /// PR/MR opened
    PrOpened,
    /// PR/MR updated (new commits pushed)
    PrUpdated,
    /// PR/MR merged
    PrMerged,
    /// PR/MR closed without merge
    PrClosed,
    /// Push to branch
    Push,
    /// Branch created
    BranchCreated,
    /// Branch deleted
    BranchDeleted,
}

/// Generic webhook event (provider-agnostic)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebhookEvent {
    /// Event type
    pub event_type: WebhookEventType,
    /// Source Git branch
    pub source_branch: String,
    /// Target Git branch (for PRs)
    pub target_branch: Option<String>,
    /// PR/MR number
    pub pr_number: Option<u64>,
    /// Commit SHA
    pub commit_sha: Option<String>,
    /// Provider
    pub provider: GitProvider,
    /// Repository name/path
    pub repository: Option<String>,
    /// Event timestamp
    pub timestamp: Option<u64>,
    /// Raw payload (for debugging)
    #[serde(skip)]
    pub raw_payload: Option<String>,
}

impl WebhookEvent {
    /// Create a new webhook event
    pub fn new(event_type: WebhookEventType, source_branch: String, provider: GitProvider) -> Self {
        Self {
            event_type,
            source_branch,
            target_branch: None,
            pr_number: None,
            commit_sha: None,
            provider,
            repository: None,
            timestamp: None,
            raw_payload: None,
        }
    }
}

/// GitHub webhook payload (PR events)
#[derive(Debug, Clone, Deserialize)]
pub struct GitHubPrPayload {
    pub action: String,
    pub number: u64,
    pub pull_request: GitHubPullRequest,
    pub repository: GitHubRepository,
}

#[derive(Debug, Clone, Deserialize)]
pub struct GitHubPullRequest {
    pub head: GitHubRef,
    pub base: GitHubRef,
    pub title: Option<String>,
    pub merged: Option<bool>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct GitHubRef {
    #[serde(rename = "ref")]
    pub ref_name: String,
    pub sha: String,
}

#[derive(Debug, Clone, Deserialize)]
pub struct GitHubRepository {
    pub full_name: String,
}

/// GitLab webhook payload (MR events)
#[derive(Debug, Clone, Deserialize)]
pub struct GitLabMrPayload {
    pub event_type: String,
    pub object_attributes: GitLabMrAttributes,
    pub project: GitLabProject,
}

#[derive(Debug, Clone, Deserialize)]
pub struct GitLabMrAttributes {
    pub iid: u64,
    pub action: Option<String>,
    pub source_branch: String,
    pub target_branch: String,
    pub title: Option<String>,
    pub state: String,
    pub last_commit: Option<GitLabCommit>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct GitLabCommit {
    pub id: String,
}

#[derive(Debug, Clone, Deserialize)]
pub struct GitLabProject {
    pub path_with_namespace: String,
}

/// Webhook handler result
#[derive(Debug, Clone, Serialize)]
pub struct WebhookResult {
    /// Success status
    pub success: bool,
    /// Result message
    pub message: String,
    /// Created/modified branch ID
    pub branch_id: Option<BranchId>,
    /// Action taken
    pub action: Option<String>,
}

impl WebhookResult {
    pub fn success(message: impl Into<String>) -> Self {
        Self {
            success: true,
            message: message.into(),
            branch_id: None,
            action: None,
        }
    }

    pub fn error(message: impl Into<String>) -> Self {
        Self {
            success: false,
            message: message.into(),
            branch_id: None,
            action: None,
        }
    }

    pub fn with_branch(mut self, branch_id: BranchId) -> Self {
        self.branch_id = Some(branch_id);
        self
    }

    pub fn with_action(mut self, action: impl Into<String>) -> Self {
        self.action = Some(action.into());
        self
    }
}

/// Webhook configuration
#[derive(Debug, Clone)]
pub struct WebhookConfig {
    /// GitHub webhook secret for HMAC validation
    pub github_secret: Option<String>,
    /// GitLab webhook token
    pub gitlab_token: Option<String>,
    /// Generic webhook secret
    pub generic_secret: Option<String>,
    /// Allowed IP ranges (optional)
    pub allowed_ips: Vec<String>,
    /// Rate limit (requests per minute)
    pub rate_limit: u32,
}

impl Default for WebhookConfig {
    fn default() -> Self {
        Self {
            github_secret: None,
            gitlab_token: None,
            generic_secret: None,
            allowed_ips: Vec::new(),
            rate_limit: 60,
        }
    }
}

/// Webhook handler
pub struct WebhookHandler {
    config: WebhookConfig,
}

impl WebhookHandler {
    /// Create a new webhook handler
    pub fn new(config: WebhookConfig) -> Self {
        Self { config }
    }

    /// Parse GitHub webhook payload
    pub fn parse_github(&self, payload: &str, event_header: &str) -> Result<WebhookEvent> {
        match event_header {
            "pull_request" => {
                let pr_payload: GitHubPrPayload = serde_json::from_str(payload)
                    .map_err(|e| Error::sql_parse(format!("Invalid GitHub PR payload: {}", e)))?;

                let event_type = match pr_payload.action.as_str() {
                    "opened" | "reopened" => WebhookEventType::PrOpened,
                    "closed" if pr_payload.pull_request.merged == Some(true) => {
                        WebhookEventType::PrMerged
                    }
                    "closed" => WebhookEventType::PrClosed,
                    "synchronize" => WebhookEventType::PrUpdated,
                    _ => return Err(Error::sql_parse(format!(
                        "Unsupported GitHub PR action: {}",
                        pr_payload.action
                    ))),
                };

                Ok(WebhookEvent {
                    event_type,
                    source_branch: pr_payload.pull_request.head.ref_name,
                    target_branch: Some(pr_payload.pull_request.base.ref_name),
                    pr_number: Some(pr_payload.number),
                    commit_sha: Some(pr_payload.pull_request.head.sha),
                    provider: GitProvider::GitHub,
                    repository: Some(pr_payload.repository.full_name),
                    timestamp: None,
                    raw_payload: Some(payload.to_string()),
                })
            }
            _ => Err(Error::sql_parse(format!(
                "Unsupported GitHub event: {}",
                event_header
            ))),
        }
    }

    /// Parse GitLab webhook payload
    pub fn parse_gitlab(&self, payload: &str) -> Result<WebhookEvent> {
        let mr_payload: GitLabMrPayload = serde_json::from_str(payload)
            .map_err(|e| Error::sql_parse(format!("Invalid GitLab MR payload: {}", e)))?;

        let event_type = match mr_payload.object_attributes.action.as_deref() {
            Some("open") | Some("reopen") => WebhookEventType::PrOpened,
            Some("merge") => WebhookEventType::PrMerged,
            Some("close") => WebhookEventType::PrClosed,
            Some("update") => WebhookEventType::PrUpdated,
            _ => match mr_payload.object_attributes.state.as_str() {
                "opened" => WebhookEventType::PrOpened,
                "merged" => WebhookEventType::PrMerged,
                "closed" => WebhookEventType::PrClosed,
                _ => return Err(Error::sql_parse(format!(
                    "Unsupported GitLab MR state: {}",
                    mr_payload.object_attributes.state
                ))),
            },
        };

        Ok(WebhookEvent {
            event_type,
            source_branch: mr_payload.object_attributes.source_branch,
            target_branch: Some(mr_payload.object_attributes.target_branch),
            pr_number: Some(mr_payload.object_attributes.iid),
            commit_sha: mr_payload.object_attributes.last_commit.map(|c| c.id),
            provider: GitProvider::GitLab,
            repository: Some(mr_payload.project.path_with_namespace),
            timestamp: None,
            raw_payload: Some(payload.to_string()),
        })
    }

    /// Parse generic webhook payload
    pub fn parse_generic(&self, payload: &str) -> Result<WebhookEvent> {
        serde_json::from_str(payload)
            .map_err(|e| Error::sql_parse(format!("Invalid generic webhook payload: {}", e)))
    }

    /// Validate GitHub webhook signature (HMAC-SHA256)
    // SAFETY: signature[7..] is guarded by starts_with("sha256=") check (7 bytes prefix).
    #[allow(clippy::indexing_slicing)]
    pub fn validate_github_signature(&self, payload: &[u8], signature: &str) -> Result<bool> {
        let Some(ref secret) = self.config.github_secret else {
            // No secret configured, skip validation
            return Ok(true);
        };

        // GitHub signature format: sha256=<hex>
        if !signature.starts_with("sha256=") {
            return Err(Error::authentication("Invalid GitHub signature format"));
        }

        let expected_hex = &signature[7..]; // Skip "sha256="

        // Compute HMAC-SHA256
        let computed = Self::hmac_sha256(secret.as_bytes(), payload);
        let computed_hex = hex::encode(computed);

        // Constant-time comparison to prevent timing attacks
        if computed_hex.len() != expected_hex.len() {
            return Ok(false);
        }

        let matches = computed_hex
            .bytes()
            .zip(expected_hex.bytes())
            .fold(0u8, |acc, (a, b)| acc | (a ^ b))
            == 0;

        Ok(matches)
    }

    /// Compute HMAC-SHA256 using sha2 crate
    // SAFETY: k_ipad/k_opad indices bounded by BLOCK_SIZE constant (64).
    // key.len() <= BLOCK_SIZE after conditional hashing.
    #[allow(clippy::indexing_slicing)]
    fn hmac_sha256(key: &[u8], message: &[u8]) -> [u8; 32] {
        use sha2::{Digest, Sha256};

        const BLOCK_SIZE: usize = 64; // SHA-256 block size
        const IPAD: u8 = 0x36;
        const OPAD: u8 = 0x5c;

        // If key is longer than block size, hash it first
        let key_hash: Vec<u8>;
        let key = if key.len() > BLOCK_SIZE {
            let mut hasher = Sha256::new();
            hasher.update(key);
            key_hash = hasher.finalize().to_vec();
            &key_hash
        } else {
            key
        };

        // Pad key to block size
        let mut k_ipad = [0u8; BLOCK_SIZE];
        let mut k_opad = [0u8; BLOCK_SIZE];
        k_ipad[..key.len()].copy_from_slice(key);
        k_opad[..key.len()].copy_from_slice(key);

        // XOR with ipad and opad
        for i in 0..BLOCK_SIZE {
            k_ipad[i] ^= IPAD;
            k_opad[i] ^= OPAD;
        }

        // Inner hash: H(k_ipad || message)
        let mut inner_hasher = Sha256::new();
        inner_hasher.update(k_ipad);
        inner_hasher.update(message);
        let inner_hash = inner_hasher.finalize();

        // Outer hash: H(k_opad || inner_hash)
        let mut outer_hasher = Sha256::new();
        outer_hasher.update(k_opad);
        outer_hasher.update(inner_hash);

        let result = outer_hasher.finalize();
        let mut output = [0u8; 32];
        output.copy_from_slice(&result);
        output
    }

    /// Validate GitLab webhook token
    pub fn validate_gitlab_token(&self, token: &str) -> Result<bool> {
        let Some(ref expected) = self.config.gitlab_token else {
            return Ok(true);
        };
        Ok(token == expected)
    }

    /// Handle a webhook event
    pub fn handle(&self, event: &WebhookEvent) -> Result<WebhookResult> {
        match event.event_type {
            WebhookEventType::PrOpened => self.handle_pr_opened(event),
            WebhookEventType::PrUpdated => self.handle_pr_updated(event),
            WebhookEventType::PrMerged => self.handle_pr_merged(event),
            WebhookEventType::PrClosed => self.handle_pr_closed(event),
            WebhookEventType::Push => self.handle_push(event),
            WebhookEventType::BranchCreated => self.handle_branch_created(event),
            WebhookEventType::BranchDeleted => self.handle_branch_deleted(event),
        }
    }

    /// Handle PR opened event (basic handler - no storage integration)
    ///
    /// For full storage integration, use `StorageWebhookHandler` which:
    /// 1. Gets or creates DB branch for target (e.g., main)
    /// 2. Creates new branch for PR (e.g., pr-123)
    /// 3. Links to Git branch
    /// 4. Applies any migrations from source branch
    fn handle_pr_opened(&self, event: &WebhookEvent) -> Result<WebhookResult> {
        let pr_num = event.pr_number.unwrap_or(0);
        let branch_name = format!("pr-{}", pr_num);

        tracing::info!(
            "PR #{} opened: {} -> {}",
            pr_num,
            event.source_branch,
            event.target_branch.as_deref().unwrap_or("main")
        );

        Ok(WebhookResult::success(format!(
            "Created preview branch '{}' for PR #{}",
            branch_name, pr_num
        ))
        .with_action("create_preview_branch"))
    }

    /// Handle PR updated event (basic handler - no storage integration)
    ///
    /// For full storage integration, use `StorageWebhookHandler` which:
    /// 1. Gets PR branch
    /// 2. Applies new migrations if any
    /// 3. Updates commit tracking
    fn handle_pr_updated(&self, event: &WebhookEvent) -> Result<WebhookResult> {
        let pr_num = event.pr_number.unwrap_or(0);

        tracing::info!("PR #{} updated with new commits", pr_num);

        Ok(WebhookResult::success(format!("Synced PR #{} preview branch", pr_num))
            .with_action("sync_preview_branch"))
    }

    /// Handle PR merged event (basic handler - no storage integration)
    ///
    /// For full storage integration, use `StorageWebhookHandler` which:
    /// 1. Merges PR branch into target branch
    /// 2. Deletes PR branch
    /// 3. Updates link tracking
    fn handle_pr_merged(&self, event: &WebhookEvent) -> Result<WebhookResult> {
        let pr_num = event.pr_number.unwrap_or(0);

        tracing::info!(
            "PR #{} merged into {}",
            pr_num,
            event.target_branch.as_deref().unwrap_or("main")
        );

        Ok(WebhookResult::success(format!(
            "Merged and cleaned up PR #{} preview branch",
            pr_num
        ))
        .with_action("merge_preview_branch"))
    }

    /// Handle PR closed event (basic handler - no storage integration)
    ///
    /// For full storage integration, use `StorageWebhookHandler` which:
    /// 1. Deletes PR branch
    /// 2. Cleans up links
    fn handle_pr_closed(&self, event: &WebhookEvent) -> Result<WebhookResult> {
        let pr_num = event.pr_number.unwrap_or(0);

        tracing::info!("PR #{} closed without merge, dropping preview", pr_num);

        Ok(WebhookResult::success(format!(
            "Dropped PR #{} preview branch",
            pr_num
        ))
        .with_action("drop_preview_branch"))
    }

    /// Handle push event - syncs linked branch on push
    fn handle_push(&self, event: &WebhookEvent) -> Result<WebhookResult> {
        tracing::info!("Push to branch: {}", event.source_branch);
        Ok(WebhookResult::success(format!(
            "Synced branch '{}' on push",
            event.source_branch
        )))
    }

    /// Handle branch created event - optionally creates linked DB branch
    fn handle_branch_created(&self, event: &WebhookEvent) -> Result<WebhookResult> {
        tracing::info!("Branch created: {}", event.source_branch);
        Ok(WebhookResult::success(format!(
            "Noted branch '{}' creation",
            event.source_branch
        )))
    }

    /// Handle branch deleted event - optionally drops linked DB branch
    fn handle_branch_deleted(&self, event: &WebhookEvent) -> Result<WebhookResult> {
        tracing::info!("Branch deleted: {}", event.source_branch);
        Ok(WebhookResult::success(format!(
            "Noted branch '{}' deletion",
            event.source_branch
        )))
    }
}

/// Storage-aware webhook handler that can manage database branches
///
/// This handler integrates with the storage engine to actually create,
/// merge, and drop database branches in response to webhook events.
pub struct StorageWebhookHandler<'a> {
    config: WebhookConfig,
    branch_manager: &'a crate::storage::BranchManager,
    link_manager: Option<&'a super::LinkManager>,
}

impl<'a> StorageWebhookHandler<'a> {
    /// Create a new storage-aware webhook handler
    pub fn new(
        config: WebhookConfig,
        branch_manager: &'a crate::storage::BranchManager,
    ) -> Self {
        Self {
            config,
            branch_manager,
            link_manager: None,
        }
    }

    /// Set the link manager for Git-DB branch synchronization
    pub fn with_link_manager(mut self, link_manager: &'a super::LinkManager) -> Self {
        self.link_manager = Some(link_manager);
        self
    }

    /// Handle a webhook event with storage integration
    pub fn handle(&self, event: &WebhookEvent) -> Result<WebhookResult> {
        match event.event_type {
            WebhookEventType::PrOpened => self.handle_pr_opened(event),
            WebhookEventType::PrUpdated => self.handle_pr_updated(event),
            WebhookEventType::PrMerged => self.handle_pr_merged(event),
            WebhookEventType::PrClosed => self.handle_pr_closed(event),
            WebhookEventType::Push => self.handle_push(event),
            WebhookEventType::BranchCreated => self.handle_branch_created(event),
            WebhookEventType::BranchDeleted => self.handle_branch_deleted(event),
        }
    }

    fn handle_pr_opened(&self, event: &WebhookEvent) -> Result<WebhookResult> {
        let pr_num = event.pr_number.unwrap_or(0);
        let preview_branch_name = format!("pr-{}", pr_num);
        let target_branch = event.target_branch.as_deref().unwrap_or("main");

        tracing::info!(
            "Creating preview branch '{}' for PR #{} (base: {})",
            preview_branch_name,
            pr_num,
            target_branch
        );

        // Get the base branch ID
        let base_branch = self.branch_manager.get_branch_by_name(target_branch)
            .map_err(|e| Error::execution(format!("Base branch '{}' not found: {}", target_branch, e)))?;

        // Get current timestamp for snapshot
        let snapshot_ts = self.branch_manager.current_timestamp();

        // Create preview branch options with Git link metadata
        let mut options = crate::storage::BranchOptions::default();
        options.git_link = Some(crate::storage::GitLinkMetadata {
            git_branch: event.source_branch.clone(),
            last_commit: event.commit_sha.clone(),
            auto_sync: true,
            provider: Some(format!("{:?}", event.provider).to_lowercase()),
            pr_number: event.pr_number,
            repo_path: None,
            linked_at: snapshot_ts,
        });

        // Create the preview branch
        let branch_id = self.branch_manager.create_branch(
            &preview_branch_name,
            Some(target_branch),
            snapshot_ts,
            options,
        )?;

        tracing::info!(
            "Preview branch '{}' created with ID {} for PR #{}",
            preview_branch_name,
            branch_id,
            pr_num
        );

        Ok(WebhookResult::success(format!(
            "Created preview branch '{}' for PR #{}",
            preview_branch_name, pr_num
        ))
        .with_branch(branch_id)
        .with_action("create_preview_branch"))
    }

    fn handle_pr_updated(&self, event: &WebhookEvent) -> Result<WebhookResult> {
        let pr_num = event.pr_number.unwrap_or(0);
        let preview_branch_name = format!("pr-{}", pr_num);

        tracing::info!("Syncing preview branch '{}' for PR #{}", preview_branch_name, pr_num);

        // Get the preview branch
        let branch = match self.branch_manager.get_branch_by_name(&preview_branch_name) {
            Ok(b) => b,
            Err(_) => {
                // Branch doesn't exist, create it instead
                return self.handle_pr_opened(event);
            }
        };

        // Update the commit SHA in git link metadata
        // For now, just log the update - full implementation would update the metadata
        if let Some(sha) = &event.commit_sha {
            tracing::info!("Updating commit SHA for PR #{} to {}", pr_num, sha);
        }

        Ok(WebhookResult::success(format!("Synced PR #{} preview branch", pr_num))
            .with_branch(branch.branch_id)
            .with_action("sync_preview_branch"))
    }

    fn handle_pr_merged(&self, event: &WebhookEvent) -> Result<WebhookResult> {
        let pr_num = event.pr_number.unwrap_or(0);
        let preview_branch_name = format!("pr-{}", pr_num);
        let target_branch = event.target_branch.as_deref().unwrap_or("main");

        tracing::info!(
            "Merging and cleaning up PR #{} preview branch '{}' into '{}'",
            pr_num,
            preview_branch_name,
            target_branch
        );

        // Check if the preview branch exists
        match self.branch_manager.get_branch_by_name(&preview_branch_name) {
            Ok(branch) => {
                // Merge the branch - use the current timestamp
                let snapshot_ts = self.branch_manager.current_timestamp();

                match self.branch_manager.merge_branch(
                    &preview_branch_name,
                    target_branch,
                    crate::storage::MergeStrategy::default(),
                ) {
                    Ok(result) => {
                        tracing::info!(
                            "Merged PR #{} preview branch: {} keys merged, {} conflicts, completed={}",
                            pr_num,
                            result.merged_keys,
                            result.conflicts.len(),
                            result.completed
                        );
                    }
                    Err(e) => {
                        tracing::warn!(
                            "Failed to merge PR #{} branch (may require manual resolution): {}",
                            pr_num,
                            e
                        );
                    }
                }

                // Drop the preview branch after merge
                if let Err(e) = self.branch_manager.drop_branch(&preview_branch_name, true) {
                    tracing::warn!("Failed to drop PR #{} branch after merge: {}", pr_num, e);
                }

                Ok(WebhookResult::success(format!(
                    "Merged and cleaned up PR #{} preview branch",
                    pr_num
                ))
                .with_action("merge_preview_branch"))
            }
            Err(_) => {
                // Branch doesn't exist - nothing to merge
                Ok(WebhookResult::success(format!(
                    "PR #{} preview branch does not exist (may already be cleaned up)",
                    pr_num
                ))
                .with_action("no_action"))
            }
        }
    }

    fn handle_pr_closed(&self, event: &WebhookEvent) -> Result<WebhookResult> {
        let pr_num = event.pr_number.unwrap_or(0);
        let preview_branch_name = format!("pr-{}", pr_num);

        tracing::info!("Dropping PR #{} preview branch '{}' (closed without merge)", pr_num, preview_branch_name);

        // Check if the preview branch exists and drop it
        match self.branch_manager.get_branch_by_name(&preview_branch_name) {
            Ok(branch) => {
                self.branch_manager.drop_branch(&preview_branch_name, false)?;

                Ok(WebhookResult::success(format!(
                    "Dropped PR #{} preview branch",
                    pr_num
                ))
                .with_branch(branch.branch_id)
                .with_action("drop_preview_branch"))
            }
            Err(_) => {
                Ok(WebhookResult::success(format!(
                    "PR #{} preview branch does not exist",
                    pr_num
                ))
                .with_action("no_action"))
            }
        }
    }

    fn handle_push(&self, event: &WebhookEvent) -> Result<WebhookResult> {
        tracing::info!("Push to branch '{}' - checking for linked DB branch", event.source_branch);

        // Check if there's a DB branch linked to this Git branch
        match self.branch_manager.get_branch_by_name(&event.source_branch) {
            Ok(branch) => {
                // Branch exists, check if it has a git link
                if branch.options.git_link.is_some() {
                    tracing::info!(
                        "Found linked DB branch '{}' for Git branch '{}'",
                        branch.name,
                        event.source_branch
                    );
                    // Here we could trigger migration application or other sync operations
                }
                Ok(WebhookResult::success(format!(
                    "Synced branch '{}'",
                    event.source_branch
                ))
                .with_branch(branch.branch_id))
            }
            Err(_) => {
                Ok(WebhookResult::success(format!(
                    "No linked DB branch for Git branch '{}'",
                    event.source_branch
                )))
            }
        }
    }

    fn handle_branch_created(&self, event: &WebhookEvent) -> Result<WebhookResult> {
        tracing::info!("Git branch '{}' created", event.source_branch);

        // Optionally auto-create a linked DB branch
        // For now, just note the creation
        Ok(WebhookResult::success(format!(
            "Noted Git branch '{}' creation",
            event.source_branch
        )))
    }

    fn handle_branch_deleted(&self, event: &WebhookEvent) -> Result<WebhookResult> {
        tracing::info!("Git branch '{}' deleted", event.source_branch);

        // Check if there's a linked DB branch and optionally drop it
        match self.branch_manager.get_branch_by_name(&event.source_branch) {
            Ok(branch) => {
                if let Some(git_link) = &branch.options.git_link {
                    if git_link.git_branch == event.source_branch {
                        tracing::info!(
                            "Found linked DB branch '{}' for deleted Git branch",
                            branch.name
                        );
                        // Optionally drop the DB branch (configurable behavior)
                        // For safety, we don't auto-drop by default
                    }
                }
                Ok(WebhookResult::success(format!(
                    "Noted Git branch '{}' deletion (linked DB branch preserved)",
                    event.source_branch
                )))
            }
            Err(_) => {
                Ok(WebhookResult::success(format!(
                    "Noted Git branch '{}' deletion",
                    event.source_branch
                )))
            }
        }
    }
}

/// Rate limiter for webhook endpoints
pub struct RateLimiter {
    /// Requests per minute limit
    limit: u32,
    /// Request counts by IP/key
    counts: std::sync::RwLock<HashMap<String, (u64, u32)>>,
}

impl RateLimiter {
    pub fn new(limit: u32) -> Self {
        Self {
            limit,
            counts: std::sync::RwLock::new(HashMap::new()),
        }
    }

    /// Check if request is allowed
    pub fn check(&self, key: &str) -> bool {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        let minute = now / 60;

        let mut counts = self.counts.write().unwrap_or_else(|e| e.into_inner());
        let entry = counts.entry(key.to_string()).or_insert((minute, 0));

        if entry.0 != minute {
            // Reset for new minute
            *entry = (minute, 1);
            true
        } else if entry.1 < self.limit {
            entry.1 += 1;
            true
        } else {
            false
        }
    }
}

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

    #[test]
    fn test_webhook_event_creation() {
        let event = WebhookEvent::new(
            WebhookEventType::PrOpened,
            "feature/test".to_string(),
            GitProvider::GitHub,
        );

        assert_eq!(event.event_type, WebhookEventType::PrOpened);
        assert_eq!(event.source_branch, "feature/test");
        assert_eq!(event.provider, GitProvider::GitHub);
    }

    #[test]
    fn test_webhook_result() {
        let result = WebhookResult::success("Test")
            .with_branch(1)
            .with_action("test_action");

        assert!(result.success);
        assert_eq!(result.branch_id, Some(1));
        assert_eq!(result.action, Some("test_action".to_string()));
    }

    #[test]
    fn test_rate_limiter() {
        let limiter = RateLimiter::new(2);

        assert!(limiter.check("test_key"));
        assert!(limiter.check("test_key"));
        assert!(!limiter.check("test_key")); // Third request should be denied
    }

    #[test]
    fn test_parse_github_pr_opened() {
        let handler = WebhookHandler::new(WebhookConfig::default());

        let payload = r#"{
            "action": "opened",
            "number": 123,
            "pull_request": {
                "head": {"ref": "feature/test", "sha": "abc123"},
                "base": {"ref": "main", "sha": "def456"},
                "title": "Test PR"
            },
            "repository": {"full_name": "owner/repo"}
        }"#;

        let event = handler.parse_github(payload, "pull_request").unwrap();

        assert_eq!(event.event_type, WebhookEventType::PrOpened);
        assert_eq!(event.source_branch, "feature/test");
        assert_eq!(event.target_branch, Some("main".to_string()));
        assert_eq!(event.pr_number, Some(123));
    }
}