cull-gmail 0.1.8

Cull emails from a gmail account using the gmail API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
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
//! CLI Integration Tests for cull-gmail
//!
//! This module provides comprehensive integration testing for the CLI interface,
//! validating argument parsing, subcommand execution, configuration handling,
//! and error scenarios without requiring actual Gmail API connectivity.

use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use tempfile::TempDir;
use tokio::process::Command as AsyncCommand;

/// Test utilities and common setup for CLI integration tests
mod test_utils {
    use super::*;

    /// Test fixture containing temporary directories and mock configurations
    pub struct CliTestFixture {
        pub temp_dir: TempDir,
        pub config_dir: PathBuf,
        pub binary_path: PathBuf,
    }

    impl CliTestFixture {
        /// Create a new test fixture with temporary directory structure
        pub fn new() -> std::io::Result<Self> {
            let temp_dir = TempDir::new()?;
            let config_dir = temp_dir.path().join(".config").join("cull-gmail");
            fs::create_dir_all(&config_dir)?;

            // Use CARGO_BIN_EXE_cull-gmail, set by Cargo at compile time to the
            // actual binary path. Works correctly in workspaces and with tools
            // that override the target directory (e.g. cargo llvm-cov).
            let binary_path = PathBuf::from(env!("CARGO_BIN_EXE_cull-gmail"));

            // Validate that the binary exists
            if !binary_path.exists() {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    format!("CLI binary not found at path: {binary_path:?}"),
                ));
            }

            Ok(Self {
                temp_dir,
                config_dir,
                binary_path,
            })
        }

        /// Create a mock configuration file
        pub fn create_config_file(&self, content: &str) -> std::io::Result<PathBuf> {
            let config_file = self.config_dir.join("config.toml");
            fs::write(&config_file, content)?;
            Ok(config_file)
        }

        /// Create a mock client credentials file
        pub fn create_credentials_file(&self, content: &str) -> std::io::Result<PathBuf> {
            let creds_file = self.config_dir.join("client_secret.json");
            fs::write(&creds_file, content)?;
            Ok(creds_file)
        }

        /// Execute CLI command with arguments and environment variables
        pub fn execute_cli(
            &self,
            args: &[&str],
            env_vars: Option<HashMap<&str, &str>>,
        ) -> std::io::Result<std::process::Output> {
            let mut cmd = Command::new(&self.binary_path);
            cmd.args(args);
            cmd.env("HOME", self.temp_dir.path());
            cmd.stdout(Stdio::piped()).stderr(Stdio::piped());

            if let Some(env) = env_vars {
                for (key, value) in env {
                    cmd.env(key, value);
                }
            }

            cmd.output()
        }

        /// Execute async CLI command for testing interactive scenarios
        pub async fn execute_cli_async(
            &self,
            args: &[&str],
            env_vars: Option<HashMap<&str, &str>>,
        ) -> std::io::Result<std::process::Output> {
            let mut cmd = AsyncCommand::new(&self.binary_path);
            cmd.args(args);
            cmd.env("HOME", self.temp_dir.path());
            cmd.stdout(Stdio::piped()).stderr(Stdio::piped());

            if let Some(env) = env_vars {
                for (key, value) in env {
                    cmd.env(key, value);
                }
            }

            cmd.output().await
        }
    }

    /// Mock Gmail API responses for testing
    pub fn mock_credentials_json() -> &'static str {
        r#"{
            "installed": {
                "client_id": "test-client-id.googleusercontent.com",
                "project_id": "test-project",
                "auth_uri": "https://accounts.google.com/o/oauth2/auth",
                "token_uri": "https://oauth2.googleapis.com/token",
                "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
                "client_secret": "test-client-secret",
                "redirect_uris": ["http://localhost"]
            }
        }"#
    }

    /// Mock configuration TOML content
    pub fn mock_config_toml() -> &'static str {
        r#"
[client]
client_id = "test-client-id"
client_secret = "test-client-secret"
max_results = "100"

[[rules]]
name = "old_promotions"
query = "category:promotions older_than:30d"
action = "delete"
enabled = true

[[rules]]
name = "old_social" 
query = "category:social older_than:60d"
action = "trash"
enabled = false
"#
    }
}

/// Test CLI argument parsing and help output
mod argument_parsing_tests {
    use super::test_utils::*;

    #[test]
    fn test_cli_help_output() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        let output = fixture
            .execute_cli(&["--help"], None)
            .expect("Failed to execute CLI");

        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);

        // Verify help output contains key elements
        assert!(stdout.contains("cull-gmail"));
        assert!(stdout.contains("USAGE:") || stdout.contains("Usage:"));
        assert!(stdout.contains("labels"));
        assert!(stdout.contains("messages"));
        assert!(stdout.contains("rules"));
    }

    #[test]
    fn test_cli_version_output() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        let output = fixture
            .execute_cli(&["--version"], None)
            .expect("Failed to execute CLI");

        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);

        // Should contain version information
        assert!(stdout.contains("cull-gmail"));
        assert!(stdout.contains("0.0.10") || stdout.split_whitespace().count() >= 2);
    }

    #[test]
    fn test_verbosity_flags() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        // Test different verbosity levels
        let verbosity_tests = [
            (vec!["-v", "labels"], "WARN"),
            (vec!["-vv", "labels"], "INFO"),
            (vec!["-vvv", "labels"], "DEBUG"),
            (vec!["-vvvv", "labels"], "TRACE"),
        ];

        for (args, _expected_level) in verbosity_tests {
            let output = fixture
                .execute_cli(&args, None)
                .expect("Failed to execute CLI");

            // Command should parse successfully (may succeed with valid auth or fail gracefully)
            // The important thing is that verbosity flags are accepted (not argument parsing error)
            let exit_code = output.status.code().unwrap_or(0);
            assert!(
                exit_code != 2,
                "Exit code 2 indicates argument parsing error, got: {exit_code}"
            );
        }
    }

    #[test]
    fn test_invalid_subcommand() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        let output = fixture
            .execute_cli(&["invalid-command"], None)
            .expect("Failed to execute CLI");

        assert!(!output.status.success());
        let stderr = String::from_utf8_lossy(&output.stderr);

        // Should show error message about invalid subcommand
        assert!(stderr.contains("error:") || stderr.contains("unrecognized"));
    }
}

/// Test labels subcommand functionality
mod labels_tests {
    use super::test_utils::*;

    #[test]
    fn test_labels_help() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        let output = fixture
            .execute_cli(&["labels", "--help"], None)
            .expect("Failed to execute CLI");

        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);

        assert!(stdout.contains("labels") || stdout.contains("List Gmail labels"));
    }

    #[test]
    fn test_labels_without_credentials() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        let output = fixture
            .execute_cli(&["labels"], None)
            .expect("Failed to execute CLI");

        assert!(!output.status.success());
        let stderr = String::from_utf8_lossy(&output.stderr);

        // Should fail with configuration or authentication error (unless valid credentials exist)
        if !output.status.success() {
            assert!(
                stderr.contains("config")
                    || stderr.contains("credentials")
                    || stderr.contains("authentication")
                    || stderr.contains("client_secret")
                    || stderr.contains("OAuth")
                    || stderr.contains("token")
            );
        }
    }

    #[test]
    fn test_labels_with_mock_config() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        // Create mock configuration files
        fixture
            .create_config_file(mock_config_toml())
            .expect("Failed to create config file");
        fixture
            .create_credentials_file(mock_credentials_json())
            .expect("Failed to create credentials file");

        let output = fixture
            .execute_cli(&["labels"], None)
            .expect("Failed to execute CLI");

        // In CI/isolated environments, the test should succeed or fail gracefully
        // We mainly test that config files are being found and processed
        let stderr = String::from_utf8_lossy(&output.stderr);

        // Test passes if any of these conditions are met:
        // 1. Command succeeds with real credentials
        // 2. Command fails but found the config files (not "config file not found")
        // 3. Command fails at OAuth/authentication step (normal for mock data)
        let config_found =
            !stderr.contains("config file not found") && !stderr.contains("No such file");
        let auth_related_failure = stderr.contains("OAuth")
            || stderr.contains("authentication")
            || stderr.contains("token")
            || stderr.contains("credentials")
            || stderr.contains("client");

        assert!(
            output.status.success() || config_found || auth_related_failure,
            "Command failed unexpectedly. Exit code: {:?}, stderr: {}",
            output.status.code(),
            stderr
        );
    }
}

/// Test messages subcommand functionality  
mod messages_tests {
    use super::test_utils::*;

    #[test]
    fn test_messages_help() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        let output = fixture
            .execute_cli(&["messages", "--help"], None)
            .expect("Failed to execute CLI");

        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);

        assert!(stdout.contains("messages"));
        assert!(stdout.contains("query") || stdout.contains("QUERY"));
    }

    #[test]
    fn test_messages_list_action() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        let output = fixture
            .execute_cli(&["messages", "--query", "in:inbox", "list"], None)
            .expect("Failed to execute CLI");

        // Should parse arguments correctly (may succeed or fail gracefully, but not with parse error)
        let exit_code = output.status.code().unwrap_or(0);
        assert!(
            exit_code != 2,
            "Exit code 2 indicates argument parsing error, got: {exit_code}"
        );
    }

    #[test]
    fn test_messages_trash_action() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        let output = fixture
            .execute_cli(&["messages", "--query", "in:spam", "trash"], None)
            .expect("Failed to execute CLI");

        // Trash command should be accepted (not argument parsing error)
        let exit_code = output.status.code().unwrap_or(0);
        assert!(
            exit_code != 2,
            "Exit code 2 indicates argument parsing error, got: {exit_code}"
        );
    }

    #[test]
    fn test_messages_pagination_options() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        let output = fixture
            .execute_cli(
                &[
                    "messages",
                    "--query",
                    "in:inbox",
                    "--max-results",
                    "50",
                    "--pages",
                    "2",
                    "list",
                ],
                None,
            )
            .expect("Failed to execute CLI");

        // Pagination arguments should be accepted (not argument parsing error)
        let exit_code = output.status.code().unwrap_or(0);
        assert!(
            exit_code != 2,
            "Exit code 2 indicates argument parsing error, got: {exit_code}"
        );
    }

    #[test]
    fn test_messages_invalid_action() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        let output = fixture
            .execute_cli(&["messages", "--query", "test", "invalid-action"], None)
            .expect("Failed to execute CLI");

        assert!(!output.status.success());
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains("error:") || stderr.contains("invalid"));
    }

    #[test]
    fn test_messages_without_query() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        let output = fixture
            .execute_cli(&["messages", "list"], None)
            .expect("Failed to execute CLI");

        // Messages list should work with or without explicit query (may use defaults)
        // The test validates that the command is well-formed, not the query requirement
        let exit_code = output.status.code().unwrap_or(0);
        assert!(
            exit_code != 2,
            "Exit code 2 indicates argument parsing error, got: {exit_code}"
        );
    }
}

/// Test rules subcommand functionality
mod rules_tests {
    use super::test_utils::*;
    use std::collections::HashMap;
    use std::fs;

    #[test]
    fn test_rules_help() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        let output = fixture
            .execute_cli(&["rules", "--help"], None)
            .expect("Failed to execute CLI");

        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);

        assert!(stdout.contains("rules"));
        assert!(stdout.contains("config") || stdout.contains("run"));
    }

    #[test]
    fn test_rules_config_subcommand() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        let output = fixture
            .execute_cli(&["rules", "config"], None)
            .expect("Failed to execute CLI");

        // Should attempt to create/display config
        let stdout = String::from_utf8_lossy(&output.stdout);
        let stderr = String::from_utf8_lossy(&output.stderr);

        // Should either succeed or show meaningful output about config
        assert!(
            output.status.success()
                || stdout.contains("config")
                || stderr.contains("config")
                || stdout.contains("toml")
                || stderr.contains("toml")
        );
    }

    #[test]
    fn test_rules_run_without_config() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        let output = fixture
            .execute_cli(&["rules", "run"], None)
            .expect("Failed to execute CLI");

        // Should fail gracefully when no config is found
        assert!(!output.status.success());
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.contains("config") || stderr.contains("file") || stderr.contains("not found")
        );
    }

    #[test]
    #[ignore = "This test requires OAuth and may hang in CI environments"]
    fn test_rules_run_with_config() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        // Create config files and credentials in both supported locations
        fixture
            .create_config_file(mock_config_toml())
            .expect("Failed to create config file");
        fixture
            .create_credentials_file(mock_credentials_json())
            .expect("Failed to create credentials file");

        // Also create legacy config path
        let legacy_dir = fixture.temp_dir.path().join(".cull-gmail");
        fs::create_dir_all(&legacy_dir).expect("Failed to create legacy config directory");
        let legacy_config_path = legacy_dir.join("cull-gmail.toml");
        fs::write(&legacy_config_path, mock_config_toml()).expect("Failed to write legacy config");
        let legacy_creds_path = legacy_dir.join("credential.json");
        fs::write(&legacy_creds_path, mock_credentials_json())
            .expect("Failed to write legacy credentials");

        // Add environment variables to prevent long hangs during OAuth attempts
        let mut env_vars = HashMap::new();
        env_vars.insert("HTTP_TIMEOUT", "5");
        env_vars.insert("CONNECT_TIMEOUT", "3");

        let output = fixture
            .execute_cli(&["rules", "run"], Some(env_vars))
            .expect("Failed to execute CLI");

        // Should succeed or fail gracefully - mainly tests that config is found and processed
        let stderr = String::from_utf8_lossy(&output.stderr);
        let exit_code = output.status.code().unwrap_or(0);

        // Test passes if:
        // 1. Command succeeds entirely, or
        // 2. Fails with auth/credentials error (normal for mock data), or
        // 3. Fails but config was found (not "config file not found")
        let config_processed =
            !stderr.contains("config file not found") && !stderr.contains("No such file");
        let auth_failure = stderr.contains("credentials")
            || stderr.contains("authentication")
            || stderr.contains("OAuth")
            || stderr.contains("token");
        let credential_issue = stderr.contains("could not read path");

        // The main goal is to test that the rules subcommand works and config is processed
        // In CI environments, OAuth will fail with mock data, which is expected
        assert!(
            output.status.success() || auth_failure || config_processed || credential_issue,
            "Rules command failed unexpectedly. Exit code: {exit_code}, stderr: {stderr}"
        );
    }

    #[test]
    fn test_rules_run_execution() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        fixture
            .create_config_file(mock_config_toml())
            .expect("Failed to create config file");

        let output = fixture
            .execute_cli(&["rules", "run"], None)
            .expect("Failed to execute CLI");

        // Rules run command should be accepted (not argument parsing error)
        let exit_code = output.status.code().unwrap_or(0);
        assert!(
            exit_code != 2,
            "Exit code 2 indicates argument parsing error, got: {exit_code}"
        );
    }

    #[test]
    fn test_rules_config_validation() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        // Create config files in both supported locations
        fixture
            .create_config_file(mock_config_toml())
            .expect("Failed to create config file");

        // Test that rules config subcommand works (doesn't require OAuth)
        let output = fixture
            .execute_cli(&["rules", "config"], None)
            .expect("Failed to execute CLI");

        // Rules config should work without authentication
        let exit_code = output.status.code().unwrap_or(0);

        // Should not crash and should handle config processing
        assert!(
            exit_code != 139, // No segfault
            "Rules config command crashed. Exit code: {exit_code}"
        );
    }
}

/// Test configuration and environment handling
mod configuration_tests {
    use super::test_utils::*;
    use std::collections::HashMap;

    #[test]
    fn test_config_file_hierarchy() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        // Create config in expected location
        let config_content = r#"
[client]
client_id = "test-from-config"
client_secret = "secret-from-config"
"#;
        fixture
            .create_config_file(config_content)
            .expect("Failed to create config");

        // Any command should now find the config
        let output = fixture
            .execute_cli(&["labels"], None)
            .expect("Failed to execute CLI");

        let stderr = String::from_utf8_lossy(&output.stderr);

        // Should not complain about missing config anymore
        assert!(!stderr.contains("config file not found"));
    }

    #[test]
    fn test_environment_variable_precedence() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        let mut env_vars = HashMap::new();
        env_vars.insert("CULL_GMAIL_CLIENT_ID", "env-client-id");
        env_vars.insert("CULL_GMAIL_CLIENT_SECRET", "env-secret");

        let output = fixture
            .execute_cli(&["labels"], Some(env_vars))
            .expect("Failed to execute CLI");

        // Environment variables should be recognized
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(!stderr.contains("client_id"));
    }

    #[test]
    fn test_invalid_config_format() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        // Create malformed config
        fixture
            .create_config_file("invalid toml content [[[")
            .expect("Failed to create config");

        let output = fixture
            .execute_cli(&["labels"], None)
            .expect("Failed to execute CLI");

        assert!(!output.status.success());
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains("config") || stderr.contains("parse") || stderr.contains("toml"));
    }
}

/// Test error handling and edge cases
mod error_handling_tests {
    use super::test_utils::*;
    use std::collections::HashMap;
    use std::fs;

    #[test]
    fn test_graceful_keyboard_interrupt() {
        // This test would require more complex setup with signal handling
        // For now, we ensure the CLI handles missing dependencies gracefully
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        let output = fixture
            .execute_cli(&["messages", "--query", "test", "list"], None)
            .expect("Failed to execute CLI");

        // Should not crash (no segfault)
        let exit_code = output.status.code().unwrap_or(0);
        assert!(
            exit_code != 139,
            "Segmentation fault detected, got exit code: {exit_code}"
        );
    }

    #[test]
    fn test_invalid_query_syntax() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        fixture
            .create_config_file(mock_config_toml())
            .expect("Failed to create config");
        fixture
            .create_credentials_file(mock_credentials_json())
            .expect("Failed to create credentials");

        let output = fixture
            .execute_cli(
                &["messages", "--query", "invalid:query:syntax:::", "list"],
                None,
            )
            .expect("Failed to execute CLI");

        // Should handle invalid queries gracefully (no segfault)
        let exit_code = output.status.code().unwrap_or(0);
        assert!(
            exit_code != 139,
            "Segmentation fault detected, got exit code: {exit_code}"
        );
    }

    #[test]
    fn test_network_timeout_simulation() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        // Set very short timeout to trigger timeout behavior
        let mut env_vars = HashMap::new();
        env_vars.insert("HTTP_TIMEOUT", "1");
        env_vars.insert("CONNECT_TIMEOUT", "1");

        fixture
            .create_config_file(mock_config_toml())
            .expect("Failed to create config");
        fixture
            .create_credentials_file(mock_credentials_json())
            .expect("Failed to create credentials");

        let output = fixture
            .execute_cli(&["labels"], Some(env_vars))
            .expect("Failed to execute CLI");

        // In CI environments, this test mainly validates the CLI doesn't crash
        // Timeout behavior may vary depending on network configuration
        let stderr = String::from_utf8_lossy(&output.stderr);
        let exit_code = output.status.code().unwrap_or(0);

        // Test passes if:
        // 1. Command succeeds (maybe with valid credentials)
        // 2. Command fails with timeout/network errors
        // 3. Command fails with auth errors (normal for mock data)
        // 4. Command doesn't crash (no segfault)
        assert!(
            exit_code != 139, // No segfault
            "Command crashed with segfault. Exit code: {exit_code}, stderr: {stderr}"
        );

        // Optional: check for expected error types (but don't require them)
        let has_expected_errors = output.status.success()
            || stderr.contains("timeout")
            || stderr.contains("network")
            || stderr.contains("connection")
            || stderr.contains("authentication")
            || stderr.contains("OAuth")
            || stderr.contains("credentials");

        // Log additional info for debugging if needed
        if !has_expected_errors {
            eprintln!("Warning: Unexpected error type. Exit code: {exit_code}, stderr: {stderr}");
        }
    }

    #[test]
    fn test_permission_denied_scenarios() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        // Create config files in both supported locations
        let config_path = fixture
            .create_config_file(mock_config_toml())
            .expect("Failed to create config");

        // Also create legacy config path: ~/.cull-gmail/cull-gmail.toml
        let legacy_dir = fixture.temp_dir.path().join(".cull-gmail");
        fs::create_dir_all(&legacy_dir).expect("Failed to create legacy config directory");
        let legacy_config_path = legacy_dir.join("cull-gmail.toml");
        fs::write(&legacy_config_path, mock_config_toml()).expect("Failed to write legacy config");

        // Try to remove read permissions from both config files (this might not work on all systems/CI)
        let permission_change_worked = {
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                let restrict_both = [
                    fs::metadata(&config_path).ok().and_then(|metadata| {
                        let mut perms = metadata.permissions();
                        perms.set_mode(0o000);
                        fs::set_permissions(&config_path, perms).ok()
                    }),
                    fs::metadata(&legacy_config_path).ok().and_then(|metadata| {
                        let mut perms = metadata.permissions();
                        perms.set_mode(0o000);
                        fs::set_permissions(&legacy_config_path, perms).ok()
                    }),
                ];
                restrict_both.iter().any(|result| result.is_some())
            }
            #[cfg(not(unix))]
            {
                false // Permission manipulation not supported on non-Unix
            }
        };

        let output = fixture
            .execute_cli(&["labels"], None)
            .expect("Failed to execute CLI");

        let stderr = String::from_utf8_lossy(&output.stderr);
        let exit_code = output.status.code().unwrap_or(0);

        // Test behavior depends on whether permission change worked
        if permission_change_worked {
            // If permissions were successfully restricted, expect permission-related errors
            assert!(
                !output.status.success()
                    && (stderr.contains("permission")
                        || stderr.contains("access")
                        || stderr.contains("denied")
                        || stderr.contains("Permission denied")),
                "Expected permission error when config file is unreadable. Exit code: {exit_code}, stderr: {stderr}"
            );
        } else {
            // If permission change didn't work (CI/containerized environments),
            // just ensure the command doesn't crash
            assert!(
                exit_code != 139, // No segfault
                "Command should not crash even if permission test cannot run. Exit code: {exit_code}, stderr: {stderr}"
            );
        }
    }
}

/// Async integration tests for concurrent operations
mod async_integration_tests {
    use super::test_utils::*;

    #[tokio::test]
    async fn test_concurrent_cli_executions() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        fixture
            .create_config_file(mock_config_toml())
            .expect("Failed to create config");

        // Execute multiple CLI commands concurrently
        let tasks = vec![
            fixture.execute_cli_async(&["labels", "--help"], None),
            fixture.execute_cli_async(&["messages", "--help"], None),
            fixture.execute_cli_async(&["rules", "--help"], None),
        ];

        let results = futures::future::join_all(tasks).await;

        // All help commands should succeed
        for result in results {
            let output = result.expect("Failed to execute CLI");
            assert!(output.status.success());
        }
    }

    #[tokio::test]
    async fn test_async_command_timeout() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");

        fixture
            .create_config_file(mock_config_toml())
            .expect("Failed to create config");
        fixture
            .create_credentials_file(mock_credentials_json())
            .expect("Failed to create credentials");

        // Test with timeout
        let result = tokio::time::timeout(
            std::time::Duration::from_secs(30),
            fixture.execute_cli_async(&["labels"], None),
        )
        .await;

        match result {
            Ok(output) => {
                let output = output.expect("Failed to execute CLI");
                // Command completed within timeout (no segfault)
                let exit_code = output.status.code().unwrap_or(0);
                assert!(
                    exit_code != 139,
                    "Segmentation fault detected, got exit code: {exit_code}"
                );
            }
            Err(_) => {
                // Timeout occurred - this is acceptable for integration tests
                // as we may not have real credentials
            }
        }
    }
}

// --- rules validate tests ---

#[cfg(test)]
mod rules_validate_tests {
    use super::test_utils::CliTestFixture;
    use std::fs;

    fn valid_rules_toml() -> &'static str {
        r#"
[rules."1"]
id = 1
retention = "d:30"
labels = ["test-label"]
action = "Trash"
"#
    }

    fn invalid_rules_toml() -> &'static str {
        r#"
[rules."1"]
id = 1
retention = ""
labels = []
action = "bad-action"
"#
    }

    fn duplicate_label_rules_toml() -> &'static str {
        r#"
[rules."1"]
id = 1
retention = "d:30"
labels = ["shared"]
action = "Trash"

[rules."2"]
id = 2
retention = "d:60"
labels = ["shared"]
action = "Trash"
"#
    }

    #[test]
    fn test_rules_validate_valid_file_exits_zero() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");
        let rules_file = fixture.temp_dir.path().join("rules.toml");
        fs::write(&rules_file, valid_rules_toml()).unwrap();

        let output = fixture
            .execute_cli(&["rules", rules_file.to_str().unwrap(), "validate"], None)
            .expect("Failed to execute CLI");

        assert!(
            output.status.success(),
            "Expected exit 0 for valid rules, got: {}\nstdout: {}\nstderr: {}",
            output.status,
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr),
        );
    }

    #[test]
    fn test_rules_validate_invalid_file_exits_nonzero() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");
        let rules_file = fixture.temp_dir.path().join("rules.toml");
        fs::write(&rules_file, invalid_rules_toml()).unwrap();

        let output = fixture
            .execute_cli(&["rules", rules_file.to_str().unwrap(), "validate"], None)
            .expect("Failed to execute CLI");

        assert!(
            !output.status.success(),
            "Expected non-zero exit for invalid rules"
        );
        let stderr = String::from_utf8_lossy(&output.stderr);
        let stdout = String::from_utf8_lossy(&output.stdout);
        let combined = format!("{stdout}{stderr}");
        assert!(
            combined.contains("Rule #1"),
            "Expected issue output mentioning rule #1, got: {combined}"
        );
    }

    #[test]
    fn test_rules_validate_duplicate_label_exits_nonzero() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");
        let rules_file = fixture.temp_dir.path().join("rules.toml");
        fs::write(&rules_file, duplicate_label_rules_toml()).unwrap();

        let output = fixture
            .execute_cli(&["rules", rules_file.to_str().unwrap(), "validate"], None)
            .expect("Failed to execute CLI");

        assert!(
            !output.status.success(),
            "Expected non-zero exit for duplicate label rules"
        );
        let stdout = String::from_utf8_lossy(&output.stdout);
        let stderr = String::from_utf8_lossy(&output.stderr);
        let combined = format!("{stdout}{stderr}");
        assert!(
            combined.contains("shared"),
            "Expected output mentioning 'shared' label, got: {combined}"
        );
    }

    #[test]
    fn test_rules_validate_missing_file_exits_nonzero() {
        let fixture = CliTestFixture::new().expect("Failed to create test fixture");
        let rules_file = fixture.temp_dir.path().join("nonexistent.toml");

        let output = fixture
            .execute_cli(&["rules", rules_file.to_str().unwrap(), "validate"], None)
            .expect("Failed to execute CLI");

        assert!(
            !output.status.success(),
            "Expected non-zero exit for missing rules file"
        );
    }
}