jirust-cli 0.17.5

A CLI tool to interact with Jira
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
use async_trait::async_trait;
use jira_v3_openapi::additional_apis::issue_attachments_api::add_attachment;
use jira_v3_openapi::apis::issue_search_api::search_and_reconsile_issues_using_jql_post;
use jira_v3_openapi::apis::issues_api::*;
use jira_v3_openapi::models::user::AccountType;
use jira_v3_openapi::models::{
    Attachment, CreatedIssue, IssueBean, IssueTransition, SearchAndReconcileRequestBean,
    Transitions, User,
};
use jira_v3_openapi::{apis::configuration::Configuration, models::IssueUpdateDetails};
use serde_json::Value;
use std::collections::HashMap;
use std::io::Error;
use std::path::Path;

#[cfg(test)]
use mockall::automock;

#[cfg(feature = "attachment_scan")]
use crate::config::config_file::YaraSection;
#[cfg(feature = "attachment_scan")]
use crate::utils::cached_scanner::CachedYaraScanner;

use crate::args::commands::TransitionArgs;
use crate::{
    args::commands::IssueArgs,
    config::config_file::{AuthData, ConfigFile},
};

/// Issue command runner
/// This struct is responsible for running the issue command
/// It uses the Jira API to perform the operations
///
/// # Fields
///
/// * `cfg` - Configuration object
pub struct IssueCmdRunner {
    /// Configuration object
    cfg: Configuration,
    #[cfg(feature = "attachment_scan")]
    yara_config: YaraSection,
}

/// Implementation of IssueCmdRunner
///
/// # Methods
///
/// * `new` - Creates a new instance of IssueCmdRunner
/// * `assign_jira_issue` - Assigns a Jira issue to a user
/// * `create_jira_issue` - Creates a Jira issue
/// * `delete_jira_issue` - Deletes a Jira issue
/// * `get_jira_issue` - Gets a Jira issue
/// * `transition_jira_issue` - Transitions a Jira issue
/// * `update_jira_issue` - Updates a Jira issue
/// * `get_issue_available_transitions` - Gets available transitions for a Jira issue
impl IssueCmdRunner {
    /// Creates a new instance of IssueCmdRunner
    ///
    /// # Arguments
    ///
    /// * `cfg_file` - Configuration file
    ///
    /// # Returns
    ///
    /// * `IssueCmdRunner` - Instance of IssueCmdRunner
    ///
    /// # Examples
    ///
    /// ```
    /// use jirust_cli::config::config_file::{ConfigFile, YaraSection};
    /// use jirust_cli::runners::jira_cmd_runners::issue_cmd_runner::IssueCmdRunner;
    /// use toml::Table;
    ///
    /// let cfg_file = ConfigFile::new("dXNlcm5hbWU6YXBpX2tleQ==".to_string(), "jira_url".to_string(), "standard_resolution".to_string(), "standard_resolution_comment".to_string(), Table::new(), YaraSection::default());
    ///
    /// let issue_cmd_runner = IssueCmdRunner::new(&cfg_file);
    /// ```
    pub fn new(cfg_file: &ConfigFile) -> IssueCmdRunner {
        let mut config = Configuration::new();
        let auth_data = AuthData::from_base64(cfg_file.get_auth_key());
        config.base_path = cfg_file.get_jira_url().to_string();
        config.basic_auth = Some((auth_data.0, Some(auth_data.1)));
        IssueCmdRunner {
            cfg: config,
            #[cfg(feature = "attachment_scan")]
            yara_config: cfg_file.get_yara_section().clone(),
        }
    }

    /// Assigns a Jira issue to a user
    ///
    /// # Arguments
    ///
    /// * `params` - Issue command parameters
    ///
    /// # Returns
    ///
    /// * `Value` - JSON value
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use jirust_cli::runners::jira_cmd_runners::issue_cmd_runner::{IssueCmdRunner, IssueCmdParams};
    /// use jirust_cli::config::config_file::{ConfigFile, YaraSection};
    /// use toml::Table;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # tokio_test::block_on(async {
    /// let cfg_file = ConfigFile::new("dXNlcm5hbWU6YXBpX2tleQ==".to_string(), "jira_url".to_string(), "standard_resolution".to_string(), "standard_resolution_comment".to_string(), Table::new(), YaraSection::default());
    /// let issue_cmd_runner = IssueCmdRunner::new(&cfg_file);
    /// let mut params = IssueCmdParams::new();
    /// params.assignee = Some("assignee".to_string());
    ///
    /// let result = issue_cmd_runner.assign_jira_issue(params).await?;
    /// # Ok(())
    /// # })
    /// # }
    /// ```
    pub async fn assign_jira_issue(
        &self,
        params: IssueCmdParams,
    ) -> Result<Value, Box<dyn std::error::Error>> {
        let user_data = User {
            account_id: Some(params.assignee.expect("Assignee is required")),
            account_type: Some(AccountType::Atlassian),
            ..Default::default()
        };

        let i_key = if let Some(key) = &params.issue_key {
            key.as_str()
        } else {
            return Err(Box::new(Error::other(
                "Error assigning issue: Empty issue key".to_string(),
            )));
        };

        Ok(assign_issue(&self.cfg, i_key, user_data).await?)
    }

    /// Attaches a file to a Jira issue
    ///
    /// # Arguments
    ///
    /// * `params` - Issue command parameters
    ///
    /// # Returns
    ///
    /// * `Attachment` - Attachment object
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use jirust_cli::runners::jira_cmd_runners::issue_cmd_runner::{IssueCmdRunner, IssueCmdParams};
    /// use jirust_cli::config::config_file::{ConfigFile, YaraSection};
    /// use toml::Table;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # tokio_test::block_on(async {
    /// let cfg_file = ConfigFile::new("dXNlcm5hbWU6YXBpX2tleQ==".to_string(), "jira_url".to_string(), "standard_resolution".to_string(), "standard_resolution_comment".to_string(), Table::new(), YaraSection::default());
    /// let issue_cmd_runner = IssueCmdRunner::new(&cfg_file);
    /// let mut params = IssueCmdParams::new();
    /// params.issue_key = Some("issue_key".to_string());
    /// params.attachment_file_path = Some("path/to/file".to_string());
    ///
    /// let result = issue_cmd_runner.attach_file_to_jira_issue(params).await?;
    /// # Ok(())
    /// # })
    /// # }
    /// ```
    pub async fn attach_file_to_jira_issue(
        &self,
        params: IssueCmdParams,
    ) -> Result<Vec<Attachment>, Box<dyn std::error::Error>> {
        let i_key = if let Some(key) = &params.issue_key {
            key.as_str()
        } else {
            return Err(Box::new(Error::other(
                "Error attaching file to issue: Empty issue key".to_string(),
            )));
        };

        if let Some(path) = &params.attachment_file_path {
            let attachment_bytes = std::fs::read(path)?;
            let file_name = Path::new(path)
                .file_name()
                .and_then(|name| name.to_str())
                .unwrap_or("attachment")
                .to_string();

            #[cfg(feature = "attachment_scan")]
            let _scan_result = self.scan_bytes(&attachment_bytes).await?;

            return Ok(
                add_attachment(&self.cfg, i_key, attachment_bytes, file_name.as_str()).await?,
            );
        } else {
            Err(Box::new(Error::other(
                "Error attaching file to issue: Empty attachment file path".to_string(),
            )))
        }
    }

    #[cfg(feature = "attachment_scan")]
    async fn scan_bytes(&self, bytes: &[u8]) -> Result<Vec<String>, Box<dyn std::error::Error>> {
        let scanner = CachedYaraScanner::from_config(&self.yara_config).await?;
        let scan_result = scanner.scan_buffer(bytes).unwrap_or_else(|e| {
            eprintln!("⚠️ YARA scan failed: {}", e);
            eprintln!("   Proceeding with attachment upload anyway...");
            vec![]
        });
        if !scan_result.is_empty() {
            println!(
                "⚠️ Attachment file triggered the following YARA scanner rules: {:?}",
                scan_result
            );
        } else {
            println!("✅ No issue found by YARA scanner in the attachment file");
        }

        Ok(scan_result)
    }

    #[cfg(all(test, feature = "attachment_scan"))]
    async fn scan_bytes_with_base_dir(&self, bytes: &[u8], base_dir: std::path::PathBuf) -> Result<Vec<String>, Box<dyn std::error::Error>> {
        let scanner = CachedYaraScanner::from_config_with_base_dir(&self.yara_config, base_dir).await?;
        let scan_result = scanner.scan_buffer(bytes).unwrap_or_else(|e| {
            eprintln!("⚠️ YARA scan failed: {}", e);
            eprintln!("   Proceeding with attachment upload anyway...");
            vec![]
        });
        if !scan_result.is_empty() {
            println!(
                "⚠️ Attachment file triggered the following YARA scanner rules: {:?}",
                scan_result
            );
        } else {
            println!("✅ No issue found by YARA scanner in the attachment file");
        }

        Ok(scan_result)
    }

    /// Creates a Jira issue
    ///
    /// # Arguments
    ///
    /// * `params` - Issue command parameters
    ///
    /// # Returns
    ///
    /// * `CreatedIssue` - Created issue
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use jirust_cli::runners::jira_cmd_runners::issue_cmd_runner::{IssueCmdRunner, IssueCmdParams};
    /// use jirust_cli::config::config_file::{ConfigFile, YaraSection};
    /// use toml::Table;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # tokio_test::block_on(async {
    /// let cfg_file = ConfigFile::new("dXNlcm5hbWU6YXBpX2tleQ==".to_string(), "jira_url".to_string(), "standard_resolution".to_string(), "standard_resolution_comment".to_string(), Table::new(), YaraSection::default());
    /// let issue_cmd_runner = IssueCmdRunner::new(&cfg_file);
    /// let params = IssueCmdParams::new();
    ///
    /// let result = issue_cmd_runner.create_jira_issue(params).await?;
    /// # Ok(())
    /// # })
    /// # }
    /// ```
    pub async fn create_jira_issue(
        &self,
        params: IssueCmdParams,
    ) -> Result<CreatedIssue, Box<dyn std::error::Error>> {
        let mut issue_fields = params.issue_fields.unwrap_or_default();
        issue_fields.insert(
            "project".to_string(),
            serde_json::json!({"key": params.project_key.expect("Project Key is required to create an issue!")}),
        );
        let issue_data = IssueUpdateDetails {
            fields: Some(issue_fields),
            history_metadata: None,
            properties: None,
            transition: None,
            update: None,
        };
        Ok(create_issue(&self.cfg, issue_data, None).await?)
    }

    /// Deletes a Jira issue
    ///
    /// # Arguments
    ///
    /// * `params` - Issue command parameters
    ///
    /// # Returns
    ///
    /// * `()` - Empty tuple
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use jirust_cli::runners::jira_cmd_runners::issue_cmd_runner::{IssueCmdRunner, IssueCmdParams};
    /// use jirust_cli::config::config_file::{ConfigFile, YaraSection};
    /// use toml::Table;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # tokio_test::block_on(async {
    /// let cfg_file = ConfigFile::new("dXNlcm5hbWU6YXBpX2tleQ==".to_string(), "jira_url".to_string(), "standard_resolution".to_string(), "standard_resolution_comment".to_string(), Table::new(), YaraSection::default());
    /// let issue_cmd_runner = IssueCmdRunner::new(&cfg_file);
    /// let mut params = IssueCmdParams::new();
    /// params.issue_key = Some("issue_key".to_string());
    ///
    /// let result = issue_cmd_runner.delete_jira_issue(params).await?;
    /// # Ok(())
    /// # })
    /// # }
    /// ```
    pub async fn delete_jira_issue(
        &self,
        params: IssueCmdParams,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let i_key = if let Some(key) = &params.issue_key {
            key.as_str()
        } else {
            return Err(Box::new(Error::other(
                "Error deleting issue: Empty issue key".to_string(),
            )));
        };

        Ok(delete_issue(&self.cfg, i_key, Some("true")).await?)
    }

    /// Gets a Jira issue
    ///
    /// # Arguments
    ///
    /// * `params` - Issue command parameters
    ///
    /// # Returns
    ///
    /// * `IssueBean` - Jira issue
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use jirust_cli::runners::jira_cmd_runners::issue_cmd_runner::{IssueCmdRunner, IssueCmdParams};
    /// use jirust_cli::config::config_file::{ConfigFile, YaraSection};
    /// use toml::Table;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # tokio_test::block_on(async {
    /// let cfg_file = ConfigFile::new("dXNlcm5hbWU6YXBpX2tleQ==".to_string(), "jira_url".to_string(), "standard_resolution".to_string(), "standard_resolution_comment".to_string(), Table::new(), YaraSection::default());
    /// let issue_cmd_runner = IssueCmdRunner::new(&cfg_file);
    /// let mut params = IssueCmdParams::new();
    /// params.issue_key = Some("issue_key".to_string());
    ///
    /// let result = issue_cmd_runner.get_jira_issue(params).await?;
    /// # Ok(())
    /// # })
    /// # }
    /// ```
    pub async fn get_jira_issue(
        &self,
        params: IssueCmdParams,
    ) -> Result<IssueBean, Box<dyn std::error::Error>> {
        let i_key = if let Some(key) = &params.issue_key {
            key.as_str()
        } else {
            return Err(Box::new(Error::other(
                "Error retrieving issue: Empty issue key".to_string(),
            )));
        };
        Ok(get_issue(&self.cfg, i_key, None, None, None, None, None, None).await?)
    }

    /// This method searches for Jira issues using the provided JQL query parameters.
    ///
    /// # Arguments
    ///
    /// * `params` - Issue command parameters
    ///
    /// # Returns
    ///
    /// * `Vec<IssueBean>` - A vector of Jira issue beans
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use jirust_cli::runners::jira_cmd_runners::issue_cmd_runner::{IssueCmdRunner, IssueCmdParams};
    /// use jirust_cli::config::config_file::{ConfigFile, YaraSection};
    /// use toml::Table;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # tokio_test::block_on(async {
    /// let cfg_file = ConfigFile::new("dXNlcm5hbWU6YXBpX2tleQ==".to_string(), "jira_url".to_string(), "standard_resolution".to_string(), "standard_resolution_comment".to_string(), Table::new(), YaraSection::default());
    /// let issue_cmd_runner = IssueCmdRunner::new(&cfg_file);
    /// let mut params = IssueCmdParams::new();
    /// params.query = Some("field=value".to_string());
    ///
    /// let result = issue_cmd_runner.search_jira_issues(params).await?;
    /// # Ok(())
    /// # })
    /// # }
    /// ```
    pub async fn search_jira_issues(
        &self,
        params: IssueCmdParams,
    ) -> Result<Vec<IssueBean>, Box<dyn std::error::Error>> {
        let search_params: SearchAndReconcileRequestBean = SearchAndReconcileRequestBean {
            fields: Some(vec!["*navigable".to_string(), "-comment".to_string()]),
            jql: params.query,
            ..Default::default()
        };
        match search_and_reconsile_issues_using_jql_post(&self.cfg, search_params).await {
            Ok(result) => {
                if let Some(issues) = result.issues {
                    Ok(issues)
                } else {
                    Ok(vec![])
                }
            }
            Err(e) => Err(Box::new(e)),
        }
    }

    /// Transitions a Jira issue
    ///
    /// # Arguments
    ///
    /// * `params` - Issue command parameters
    ///
    /// # Returns
    ///
    /// * `Value` - Jira issue transition
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use jirust_cli::runners::jira_cmd_runners::issue_cmd_runner::{IssueCmdRunner, IssueCmdParams};
    /// use jirust_cli::config::config_file::{ConfigFile, YaraSection};
    /// use toml::Table;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # tokio_test::block_on(async {
    /// let cfg_file = ConfigFile::new("dXNlcm5hbWU6YXBpX2tleQ==".to_string(), "jira_url".to_string(), "standard_resolution".to_string(), "standard_resolution_comment".to_string(), Table::new(), YaraSection::default());
    /// let issue_cmd_runner = IssueCmdRunner::new(&cfg_file);
    ///
    /// let mut params = IssueCmdParams::new();
    /// params.transition = Some("transition_id".to_string());
    ///
    /// let result = issue_cmd_runner.transition_jira_issue(params).await?;
    /// # Ok(())
    /// # })
    /// # }
    /// ```
    pub async fn transition_jira_issue(
        &self,
        params: IssueCmdParams,
    ) -> Result<Value, Box<dyn std::error::Error>> {
        let i_key = if let Some(key) = &params.issue_key {
            key.as_str()
        } else {
            return Err(Box::new(Error::other(
                "Error with issue transition: Empty issue key".to_string(),
            )));
        };

        let trans = if let Some(transition) = &params.transition {
            transition.as_str()
        } else {
            return Err(Box::new(Error::other(
                "Error with issue transition: Empty transition".to_string(),
            )));
        };

        let transition = IssueTransition {
            id: Some(trans.to_string()),
            ..Default::default()
        };
        let issue_data = IssueUpdateDetails {
            fields: params.issue_fields,
            history_metadata: None,
            properties: None,
            transition: Some(transition),
            update: None,
        };
        Ok(do_transition(&self.cfg, i_key, issue_data).await?)
    }

    /// Updates a Jira issue
    ///
    /// # Arguments
    ///
    /// * `params` - Issue command parameters
    ///
    /// # Returns
    ///
    /// * `Value` - Jira issue update
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use jirust_cli::runners::jira_cmd_runners::issue_cmd_runner::{IssueCmdRunner, IssueCmdParams};
    /// use jirust_cli::config::config_file::{ConfigFile, YaraSection};
    /// use toml::Table;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # tokio_test::block_on(async {
    /// let cfg_file = ConfigFile::new("dXNlcm5hbWU6YXBpX2tleQ==".to_string(), "jira_url".to_string(), "standard_resolution".to_string(), "standard_resolution_comment".to_string(), Table::new(), YaraSection::default());
    /// let issue_cmd_runner = IssueCmdRunner::new(&cfg_file);
    /// let params = IssueCmdParams::new();
    ///
    /// let result = issue_cmd_runner.update_jira_issue(params).await?;
    /// # Ok(())
    /// # })
    /// # }
    /// ```
    pub async fn update_jira_issue(
        &self,
        params: IssueCmdParams,
    ) -> Result<Value, Box<dyn std::error::Error>> {
        let i_key = if let Some(key) = &params.issue_key {
            key.as_str()
        } else {
            return Err(Box::new(Error::other(
                "Error updating issue: Empty issue key".to_string(),
            )));
        };

        let issue_data = IssueUpdateDetails {
            fields: params.issue_fields,
            history_metadata: None,
            properties: None,
            transition: None,
            update: None,
        };
        Ok(edit_issue(
            &self.cfg,
            i_key,
            issue_data,
            None,
            None,
            None,
            Some(true),
            None,
        )
        .await?)
    }

    /// Gets available transitions for a Jira issue
    ///
    /// # Arguments
    ///
    /// * `params` - Issue command parameters
    ///
    /// # Returns
    ///
    /// * `Transitions` - Jira issue transitions
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use jirust_cli::runners::jira_cmd_runners::issue_cmd_runner::{IssueCmdRunner, IssueTransitionCmdParams};
    /// use jirust_cli::config::config_file::{ConfigFile, YaraSection};
    /// use toml::Table;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # tokio_test::block_on(async {
    /// let cfg_file = ConfigFile::new("dXNlcm5hbWU6YXBpX2tleQ==".to_string(), "jira_url".to_string(), "standard_resolution".to_string(), "standard_resolution_comment".to_string(), Table::new(), YaraSection::default());
    /// let issue_cmd_runner = IssueCmdRunner::new(&cfg_file);
    /// let mut params = IssueTransitionCmdParams::new();
    /// params.issue_key = "issue_key".to_string();
    ///
    /// let result = issue_cmd_runner.get_issue_available_transitions(params).await?;
    /// # Ok(())
    /// # })
    /// # }
    /// ```
    pub async fn get_issue_available_transitions(
        &self,
        params: IssueTransitionCmdParams,
    ) -> Result<Transitions, Box<dyn std::error::Error>> {
        Ok(get_transitions(
            &self.cfg,
            &params.issue_key,
            None,
            None,
            None,
            Some(false),
            None,
        )
        .await?)
    }
}

/// Issue command parameters
///
/// # Fields
///
/// * `project_key` - Jira project key
/// * `issue_key` - Jira issue key
/// * `issue_fields` - Jira issue fields
/// * `transition` - Jira issue transition
/// * `assignee` - Jira issue assignee
/// * `query` - Jira issue query
pub struct IssueCmdParams {
    /// Jira project key
    pub project_key: Option<String>,
    /// Jira issue key
    pub issue_key: Option<String>,
    /// Jira issue fields
    pub issue_fields: Option<HashMap<String, Value>>,
    /// Jira issue transition
    pub transition: Option<String>,
    /// Jira issue assignee
    pub assignee: Option<String>,
    /// Jira issue query
    pub query: Option<String>,
    /// Jira issue file path for attachment
    pub attachment_file_path: Option<String>,
}

/// Implementation of IssueCmdParams struct
///
/// # Methods
///
/// * `new` - Creates a new IssueCmdParams instance
impl IssueCmdParams {
    /// Creates a new IssueCmdParams instance
    ///
    /// # Returns
    ///
    /// * `IssueCmdParams` - Issue command parameters
    ///
    /// # Examples
    ///
    /// ```
    /// use jirust_cli::runners::jira_cmd_runners::issue_cmd_runner::IssueCmdParams;
    ///
    /// let params = IssueCmdParams::new();
    /// ```
    pub fn new() -> IssueCmdParams {
        IssueCmdParams {
            project_key: Some("".to_string()),
            issue_key: None,
            issue_fields: None,
            transition: None,
            assignee: None,
            query: None,
            attachment_file_path: None,
        }
    }
}

/// Implementation of From trait for IssueCmdParams struct
/// to convert IssueArgs struct to IssueCmdParams struct
impl From<&IssueArgs> for IssueCmdParams {
    /// Converts IssueArgs struct to IssueCmdParams struct
    /// to create a new IssueCmdParams instance
    ///
    /// # Arguments
    ///
    /// * `value` - IssueArgs struct
    ///
    /// # Returns
    ///
    /// * `IssueCmdParams` - Issue command parameters
    ///
    /// # Examples
    ///
    /// ```
    /// use jirust_cli::runners::jira_cmd_runners::issue_cmd_runner::IssueCmdParams;
    /// use jirust_cli::args::commands::{IssueArgs, PaginationArgs, OutputArgs, IssueActionValues};
    /// use std::collections::HashMap;
    /// use serde_json::Value;
    ///
    /// let issue_args = IssueArgs {
    ///    issue_act: IssueActionValues::Get,
    ///    project_key: Some("project_key".to_string()),
    ///    issue_key: Some("issue_key".to_string()),
    ///    issue_fields: Some(vec![("key".to_string(), r#"{ "key": "value" }"#.to_string())]),
    ///    transition_to: Some("transition_to".to_string()),
    ///    assignee: Some("assignee".to_string()),
    ///    query: None,
    ///    attachment_file_path: None,
    ///    pagination: PaginationArgs { page_size: Some(20), page_offset: None },
    ///    output: OutputArgs { output_format: None, output_type: None },
    /// };
    ///
    /// let params = IssueCmdParams::from(&issue_args);
    ///
    /// assert_eq!(params.project_key, Some("project_key".to_string()));
    /// assert_eq!(params.issue_key.unwrap(), "issue_key".to_string());
    /// assert_eq!(params.transition.unwrap(), "transition_to".to_string());
    /// assert_eq!(params.assignee.unwrap(), "assignee".to_string());
    /// ```
    fn from(value: &IssueArgs) -> Self {
        IssueCmdParams {
            project_key: value.project_key.clone(),
            issue_key: value.issue_key.clone(),
            issue_fields: Some(
                value
                    .issue_fields
                    .clone()
                    .unwrap_or_default()
                    .iter()
                    .map(|elem| {
                        (
                            elem.0.clone(),
                            serde_json::from_str(elem.1.clone().as_str()).unwrap_or(Value::Null),
                        )
                    })
                    .collect::<HashMap<_, _>>(),
            ),
            transition: value.transition_to.clone(),
            assignee: value.assignee.clone(),
            query: value.query.clone(),
            attachment_file_path: value.attachment_file_path.clone(),
        }
    }
}

/// Issue transition command parameters
///
/// # Fields
///
/// * `issue_key` - Jira issue key
pub struct IssueTransitionCmdParams {
    /// Jira issue key
    pub issue_key: String,
}

/// Implementation of IssueTransitionCmdParams struct
///
/// # Methods
///
/// * `new` - Creates a new IssueTransitionCmdParams instance
impl IssueTransitionCmdParams {
    /// Creates a new IssueTransitionCmdParams instance
    ///
    /// # Returns
    ///
    /// * `IssueTransitionCmdParams` - Issue transition command parameters
    ///
    /// # Examples
    ///
    /// ```
    /// use jirust_cli::runners::jira_cmd_runners::issue_cmd_runner::IssueTransitionCmdParams;
    ///
    /// let params = IssueTransitionCmdParams::new();
    /// ```
    pub fn new() -> IssueTransitionCmdParams {
        IssueTransitionCmdParams {
            issue_key: "".to_string(),
        }
    }
}

/// Implementation of From trait for IssueTransitionCmdParams struct
/// to convert TransitionArgs struct to IssueTransitionCmdParams struct
impl From<&TransitionArgs> for IssueTransitionCmdParams {
    /// Converts TransitionArgs struct to IssueTransitionCmdParams struct
    /// to create a new IssueTransitionCmdParams instance
    ///
    /// # Arguments
    ///
    /// * `value` - TransitionArgs struct
    ///
    /// # Returns
    ///
    /// * `IssueTransitionCmdParams` - Issue transition command parameters
    ///
    /// # Examples
    ///
    /// ```
    /// use jirust_cli::runners::jira_cmd_runners::issue_cmd_runner::IssueTransitionCmdParams;
    /// use jirust_cli::args::commands::{TransitionArgs, TransitionActionValues, OutputArgs};
    ///
    /// let transition_args = TransitionArgs {
    ///    transition_act: TransitionActionValues::List,
    ///    issue_key: "issue_key".to_string(),
    ///    output: OutputArgs { output_format: None, output_type: None },
    /// };
    ///
    /// let params = IssueTransitionCmdParams::from(&transition_args);
    ///
    /// assert_eq!(params.issue_key, "issue_key".to_string());
    /// ```
    fn from(value: &TransitionArgs) -> Self {
        IssueTransitionCmdParams {
            issue_key: value.issue_key.clone(),
        }
    }
}

/// Default implementation for IssueCmdParams struct
impl Default for IssueTransitionCmdParams {
    /// Creates a default IssueTransitionCmdParams instance
    ///
    /// # Returns
    ///
    /// A IssueTransitionCmdParams instance with default values
    ///
    /// # Examples
    ///
    /// ```
    /// use jirust_cli::runners::jira_cmd_runners::issue_cmd_runner::IssueTransitionCmdParams;
    ///
    /// let params = IssueTransitionCmdParams::default();
    ///
    /// assert_eq!(params.issue_key, "".to_string());
    /// ```
    fn default() -> Self {
        IssueTransitionCmdParams::new()
    }
}

/// Default implementation for IssueCmdParams struct
impl Default for IssueCmdParams {
    /// Creates a default IssueCmdParams instance
    ///
    /// # Returns
    ///
    /// A IssueCmdParams instance with default values
    ///
    /// # Examples
    ///
    /// ```
    /// use jirust_cli::runners::jira_cmd_runners::issue_cmd_runner::IssueCmdParams;
    ///
    /// let params = IssueCmdParams::default();
    ///
    /// assert_eq!(params.project_key, Some("".to_string()));
    /// assert_eq!(params.issue_key, None);
    /// assert_eq!(params.issue_fields, None);
    /// assert_eq!(params.transition, None);
    /// assert_eq!(params.assignee, None);
    /// ```
    fn default() -> Self {
        IssueCmdParams::new()
    }
}

/// API contract for running Jira issue operations.
#[cfg_attr(test, automock)]
#[async_trait(?Send)]
pub trait IssueCmdRunnerApi: Send + Sync {
    /// Assigns a Jira issue to a user or placeholder account.
    async fn assign_jira_issue(
        &self,
        params: IssueCmdParams,
    ) -> Result<Value, Box<dyn std::error::Error>>;

    /// Attaches a file to a Jira issue.
    async fn attach_file_to_jira_issue(
        &self,
        params: IssueCmdParams,
    ) -> Result<Vec<Attachment>, Box<dyn std::error::Error>>;

    /// Creates a Jira issue using the provided parameters.
    async fn create_jira_issue(
        &self,
        params: IssueCmdParams,
    ) -> Result<CreatedIssue, Box<dyn std::error::Error>>;

    /// Deletes a Jira issue by key.
    async fn delete_jira_issue(
        &self,
        params: IssueCmdParams,
    ) -> Result<(), Box<dyn std::error::Error>>;

    /// Retrieves a Jira issue by key.
    async fn get_jira_issue(
        &self,
        params: IssueCmdParams,
    ) -> Result<IssueBean, Box<dyn std::error::Error>>;

    /// Executes a search query and returns the matching issues.
    async fn search_jira_issues(
        &self,
        params: IssueCmdParams,
    ) -> Result<Vec<IssueBean>, Box<dyn std::error::Error>>;

    /// Transitions an issue to a new status.
    async fn transition_jira_issue(
        &self,
        params: IssueCmdParams,
    ) -> Result<Value, Box<dyn std::error::Error>>;

    /// Updates an issue fields payload.
    async fn update_jira_issue(
        &self,
        params: IssueCmdParams,
    ) -> Result<Value, Box<dyn std::error::Error>>;

    /// Fetches the available transitions for an issue.
    async fn get_issue_available_transitions(
        &self,
        params: IssueTransitionCmdParams,
    ) -> Result<Transitions, Box<dyn std::error::Error>>;
}

#[async_trait(?Send)]
impl IssueCmdRunnerApi for IssueCmdRunner {
    async fn assign_jira_issue(
        &self,
        params: IssueCmdParams,
    ) -> Result<Value, Box<dyn std::error::Error>> {
        IssueCmdRunner::assign_jira_issue(self, params).await
    }

    async fn attach_file_to_jira_issue(
        &self,
        params: IssueCmdParams,
    ) -> Result<Vec<Attachment>, Box<dyn std::error::Error>> {
        IssueCmdRunner::attach_file_to_jira_issue(self, params).await
    }

    async fn create_jira_issue(
        &self,
        params: IssueCmdParams,
    ) -> Result<CreatedIssue, Box<dyn std::error::Error>> {
        IssueCmdRunner::create_jira_issue(self, params).await
    }

    async fn delete_jira_issue(
        &self,
        params: IssueCmdParams,
    ) -> Result<(), Box<dyn std::error::Error>> {
        IssueCmdRunner::delete_jira_issue(self, params).await
    }

    async fn get_jira_issue(
        &self,
        params: IssueCmdParams,
    ) -> Result<IssueBean, Box<dyn std::error::Error>> {
        IssueCmdRunner::get_jira_issue(self, params).await
    }

    async fn search_jira_issues(
        &self,
        params: IssueCmdParams,
    ) -> Result<Vec<IssueBean>, Box<dyn std::error::Error>> {
        IssueCmdRunner::search_jira_issues(self, params).await
    }

    async fn transition_jira_issue(
        &self,
        params: IssueCmdParams,
    ) -> Result<Value, Box<dyn std::error::Error>> {
        IssueCmdRunner::transition_jira_issue(self, params).await
    }

    async fn update_jira_issue(
        &self,
        params: IssueCmdParams,
    ) -> Result<Value, Box<dyn std::error::Error>> {
        IssueCmdRunner::update_jira_issue(self, params).await
    }

    async fn get_issue_available_transitions(
        &self,
        params: IssueTransitionCmdParams,
    ) -> Result<Transitions, Box<dyn std::error::Error>> {
        IssueCmdRunner::get_issue_available_transitions(self, params).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::config_file::{ConfigFile, YaraSection};
    use std::sync::Mutex;
    use std::{env, fs};
    use tempfile::tempdir;
    use toml::Table;

    static ENV_MUTEX: Mutex<()> = Mutex::new(());

    fn basic_config() -> ConfigFile {
        ConfigFile::new(
            "dGVzdDp0b2tlbg==".to_string(),
            "https://example.atlassian.net".to_string(),
            "Done".to_string(),
            "Completed".to_string(),
            Table::new(),
            YaraSection::default(),
        )
    }

    #[tokio::test]
    async fn attach_without_issue_key_returns_error() {
        let runner = IssueCmdRunner::new(&basic_config());
        let mut params = IssueCmdParams::new();
        params.attachment_file_path = Some("/tmp/file.txt".to_string());

        let result = runner.attach_file_to_jira_issue(params).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Empty issue key"));
    }

    #[tokio::test]
    async fn attach_without_file_path_returns_error() {
        let runner = IssueCmdRunner::new(&basic_config());
        let mut params = IssueCmdParams::new();
        params.issue_key = Some("TEST-123".to_string());

        let result = runner.attach_file_to_jira_issue(params).await;
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Empty attachment file path")
        );
    }

    #[cfg(feature = "attachment_scan")]
    #[tokio::test]
    async fn scan_bytes_uses_local_rules() {
        let _guard = ENV_MUTEX.lock().unwrap();
        let temp_home = tempdir().expect("temp HOME");
        let base_dir = temp_home.path().join(".jirust-cli");
        let rules_dir = base_dir.join("rules");
        fs::create_dir_all(&rules_dir).expect("create rules dir");

        fs::write(rules_dir.join(".version"), "v1").expect("write version marker");
        fs::write(
            rules_dir.join("test_rule.yar"),
            r#"
rule TestRule {
  strings:
    $a = "hitme"
  condition:
    $a
}
"#,
        )
        .expect("write yara rule");

        let config = ConfigFile::new(
            "dGVzdDp0b2tlbg==".to_string(),
            "https://example.atlassian.net".to_string(),
            "Done".to_string(),
            "Completed".to_string(),
            Table::new(),
            YaraSection::new(
                "local_rules.zip".to_string(),
                "rules".to_string(),
                "yara_rules.cache".to_string(),
                "yara_rules.cache.version".to_string(),
            ),
        );

        let runner = IssueCmdRunner::new(&config);
        let matches = runner
            .scan_bytes_with_base_dir(b"hitme", base_dir.clone())
            .await
            .expect("scan should succeed");

        assert!(matches.contains(&"TestRule".to_string()));
        assert!(base_dir.join("yara_rules.cache").exists());
        assert!(base_dir.join("yara_rules.cache.version").exists());
    }
}