1# frozen_string_literal: true
2
3module QA
4  module Vendor
5    module Jira
6      class JiraAPI
7        include Scenario::Actable
8        include Support::API
9
10        DEFAULT_ISSUE_SUMMARY = 'REST ye merry gentlemen.'
11        DEFAULT_ISSUE_DESCRIPTION = 'Creating of an issue using project keys and issue type names using the REST API'
12
13        def base_url
14          host = QA::Runtime::Env.jira_hostname || 'localhost'
15
16          "http://#{host}:8080"
17        end
18
19        def api_url
20          "#{base_url}/rest/api/2"
21        end
22
23        def fetch_issue(issue_key)
24          response = get("#{api_url}/issue/#{issue_key}",
25                         user: Runtime::Env.jira_admin_username,
26                         password: Runtime::Env.jira_admin_password)
27
28          parse_body(response)
29        end
30
31        def create_project(project_key = "GL#{SecureRandom.hex(4)}".upcase)
32          payload = {
33            key: project_key,
34            name: "Project #{project_key}",
35            description: "New Project #{project_key}",
36            lead: Runtime::Env.jira_admin_username,
37            projectTypeKey: 'software'
38          }
39          response = post(
40            "#{api_url}/project",
41            payload.to_json,
42            headers: { 'Content-Type' => 'application/json' },
43            user: Runtime::Env.jira_admin_username,
44            password: Runtime::Env.jira_admin_password)
45
46          returned_project_key = parse_body(response)[:key]
47
48          QA::Runtime::Logger.debug("Created JIRA project with key: '#{project_key}'")
49
50          returned_project_key
51        end
52
53        def create_issue(
54          jira_project_key,
55          issue_type: 'Bug',
56          summary: DEFAULT_ISSUE_SUMMARY,
57          description: DEFAULT_ISSUE_DESCRIPTION
58        )
59          payload = {
60            fields: {
61              project: {
62                key: jira_project_key
63              },
64              summary: summary,
65              description: description,
66              issuetype: {
67                name: issue_type
68              }
69            }
70          }
71
72          response = post(
73            "#{api_url}/issue",
74            payload.to_json,
75            headers: { 'Content-Type': 'application/json' },
76            user: Runtime::Env.jira_admin_username,
77            password: Runtime::Env.jira_admin_password)
78
79          issue_key = parse_body(response)[:key]
80
81          QA::Runtime::Logger.debug("Created JIRA issue with key: '#{issue_key}'")
82
83          issue_key
84        end
85      end
86    end
87  end
88end
89