package jira

import (
	"encoding/json"
	"fmt"
	"testing"
)

const jsonStr = `
{
  "timestamp": 1655098905977,
  "webhookEvent": "jira:issue_updated",
  "issue_event_type_name": "issue_updated",
  "user": {
    "self": "https://jira.tidbcloud.com/rest/api/2/user?username=charles.m%40pingcap.com",
    "name": "charles.m@pingcap.com",
    "key": "JIRAUSER10936",
    "emailAddress": "charles.m@pingcap.com",
    "avatarUrls": {
      "48x48": "https://www.gravatar.com/avatar/b0de58a1e5f6dd3070cdde3cc0908cba?d=mm&s=48",
      "24x24": "https://www.gravatar.com/avatar/b0de58a1e5f6dd3070cdde3cc0908cba?d=mm&s=24",
      "16x16": "https://www.gravatar.com/avatar/b0de58a1e5f6dd3070cdde3cc0908cba?d=mm&s=16",
      "32x32": "https://www.gravatar.com/avatar/b0de58a1e5f6dd3070cdde3cc0908cba?d=mm&s=32"
    },
    "displayName": "Charles M",
    "active": true,
    "timeZone": "GMT"
  },
  "issue": {
    "id": "18124",
    "self": "https://jira.tidbcloud.com/rest/api/2/issue/18124",
    "key": "TCA-106",
    "fields": {
      "issuetype": {
        "self": "https://jira.tidbcloud.com/rest/api/2/issuetype/10002",
        "id": "10002",
        "description": "A task that needs to be done.",
        "iconUrl": "https://jira.tidbcloud.com/secure/viewavatar?size=xsmall&avatarId=10318&avatarType=issuetype",
        "name": "Task",
        "subtask": false,
        "avatarId": 10318
      },
      "components": [],
      "timespent": null,
      "timeoriginalestimate": null,
      "description": "Labels:\n - alertname = AwsSharedProviderTiDBClusterUnavailable\n - cluster = base/eks/us-west-2\n - component = aws-shared-provider\n - endpoint = metric\n - instance = 10.0.102.83:8080\n - job = dispatcher-metrics\n - kubernetes = prod-us-west-2-f01\n - namespace = prod-1372813089195441284\n - network = aws-free-tier-us-west-2\n - phase = Unavailable\n - pod = dispatcher-6cb88f8c98-lv9xr\n - prometheus = monitoring/k8s\n - provider = eks\n - provider_type = aws-free-tier\n - region = us-west-2\n - service = dispatcher-metrics\n - severity = critical\n - tidb = 1379661944615924077\n - type = infra\n\nAnnotations:\n - description = Cluster 1379661944615924077 under kubernetes prod-us-west-2-f01 is currently unavailable.\n\nSource: http://prometheus-k8s-0:9090/graph?g0.expr=dispatcher_cluster_status_phase%7Bphase%3D%22Unavailable%22%7D+%3D%3D+1&g0.tab=1\n",
      "project": {
        "self": "https://jira.tidbcloud.com/rest/api/2/project/10415",
        "id": "10415",
        "key": "TCA",
        "name": "TiDBCloud-Alert",
        "projectTypeKey": "business",
        "avatarUrls": {
          "48x48": "https://jira.tidbcloud.com/secure/projectavatar?pid=10415&avatarId=10209",
          "24x24": "https://jira.tidbcloud.com/secure/projectavatar?size=small&pid=10415&avatarId=10209",
          "16x16": "https://jira.tidbcloud.com/secure/projectavatar?size=xsmall&pid=10415&avatarId=10209",
          "32x32": "https://jira.tidbcloud.com/secure/projectavatar?size=medium&pid=10415&avatarId=10209"
        }
      },
      "fixVersions": [],
      "aggregatetimespent": null,
      "resolution": null,
      "timetracking": {},
      "customfield_10500": null,
      "customfield_10105": null,
      "customfield_10501": null,
      "customfield_10106": null,
      "customfield_10502": null,
      "customfield_10503": null,
      "attachment": [],
      "customfield_10504": null,
      "aggregatetimeestimate": null,
      "resolutiondate": null,
      "workratio": -1,
      "summary": "[FIRING:1] AwsSharedProviderTiDBClusterUnavailable",
      "lastViewed": null,
      "watches": {
        "self": "https://jira.tidbcloud.com/rest/api/2/issue/TCA-106/watchers",
        "watchCount": 1,
        "isWatching": true
      },
      "creator": {
        "self": "https://jira.tidbcloud.com/rest/api/2/user?username=charles.m%40pingcap.com",
        "name": "charles.m@pingcap.com",
        "key": "JIRAUSER10936",
        "emailAddress": "charles.m@pingcap.com",
        "avatarUrls": {
          "48x48": "https://www.gravatar.com/avatar/b0de58a1e5f6dd3070cdde3cc0908cba?d=mm&s=48",
          "24x24": "https://www.gravatar.com/avatar/b0de58a1e5f6dd3070cdde3cc0908cba?d=mm&s=24",
          "16x16": "https://www.gravatar.com/avatar/b0de58a1e5f6dd3070cdde3cc0908cba?d=mm&s=16",
          "32x32": "https://www.gravatar.com/avatar/b0de58a1e5f6dd3070cdde3cc0908cba?d=mm&s=32"
        },
        "displayName": "Charles M",
        "active": true,
        "timeZone": "GMT"
      },
      "subtasks": [],
      "created": "2022-05-30T03:48:37.000+0000",
      "reporter": {
        "self": "https://jira.tidbcloud.com/rest/api/2/user?username=charles.m%40pingcap.com",
        "name": "charles.m@pingcap.com",
        "key": "JIRAUSER10936",
        "emailAddress": "charles.m@pingcap.com",
        "avatarUrls": {
          "48x48": "https://www.gravatar.com/avatar/b0de58a1e5f6dd3070cdde3cc0908cba?d=mm&s=48",
          "24x24": "https://www.gravatar.com/avatar/b0de58a1e5f6dd3070cdde3cc0908cba?d=mm&s=24",
          "16x16": "https://www.gravatar.com/avatar/b0de58a1e5f6dd3070cdde3cc0908cba?d=mm&s=16",
          "32x32": "https://www.gravatar.com/avatar/b0de58a1e5f6dd3070cdde3cc0908cba?d=mm&s=32"
        },
        "displayName": "Charles M",
        "active": true,
        "timeZone": "GMT"
      },
      "customfield_10000": "{summaryBean=com.atlassian.jira.plugin.devstatus.rest.SummaryBean@1d6fd346[summary={pullrequest=com.atlassian.jira.plugin.devstatus.rest.SummaryItemBean@ee2f047[overall=PullRequestOverallBean{stateCount=0, state='OPEN', details=PullRequestOverallDetails{openCount=0, mergedCount=0, declinedCount=0}},byInstanceType={}], build=com.atlassian.jira.plugin.devstatus.rest.SummaryItemBean@2f9beb3f[overall=com.atlassian.jira.plugin.devstatus.summary.beans.BuildOverallBean@36e25643[failedBuildCount=0,successfulBuildCount=0,unknownBuildCount=0,count=0,lastUpdated=<null>,lastUpdatedTimestamp=<null>],byInstanceType={}], review=com.atlassian.jira.plugin.devstatus.rest.SummaryItemBean@7786b981[overall=com.atlassian.jira.plugin.devstatus.summary.beans.ReviewsOverallBean@548836d6[stateCount=0,state=<null>,dueDate=<null>,overDue=false,count=0,lastUpdated=<null>,lastUpdatedTimestamp=<null>],byInstanceType={}], deployment-environment=com.atlassian.jira.plugin.devstatus.rest.SummaryItemBean@243aed6b[overall=com.atlassian.jira.plugin.devstatus.summary.beans.DeploymentOverallBean@cef7e1[topEnvironments=[],showProjects=false,successfulCount=0,count=0,lastUpdated=<null>,lastUpdatedTimestamp=<null>],byInstanceType={}], repository=com.atlassian.jira.plugin.devstatus.rest.SummaryItemBean@42c61cc8[overall=com.atlassian.jira.plugin.devstatus.summary.beans.CommitOverallBean@57edbcc0[count=0,lastUpdated=<null>,lastUpdatedTimestamp=<null>],byInstanceType={}], branch=com.atlassian.jira.plugin.devstatus.rest.SummaryItemBean@244f42e3[overall=com.atlassian.jira.plugin.devstatus.summary.beans.BranchOverallBean@53c9c874[count=0,lastUpdated=<null>,lastUpdatedTimestamp=<null>],byInstanceType={}]},errors=[],configErrors=[]], devSummaryJson={\"cachedValue\":{\"errors\":[],\"configErrors\":[],\"summary\":{\"pullrequest\":{\"overall\":{\"count\":0,\"lastUpdated\":null,\"stateCount\":0,\"state\":\"OPEN\",\"details\":{\"openCount\":0,\"mergedCount\":0,\"declinedCount\":0,\"total\":0},\"open\":true},\"byInstanceType\":{}},\"build\":{\"overall\":{\"count\":0,\"lastUpdated\":null,\"failedBuildCount\":0,\"successfulBuildCount\":0,\"unknownBuildCount\":0},\"byInstanceType\":{}},\"review\":{\"overall\":{\"count\":0,\"lastUpdated\":null,\"stateCount\":0,\"state\":null,\"dueDate\":null,\"overDue\":false,\"completed\":false},\"byInstanceType\":{}},\"deployment-environment\":{\"overall\":{\"count\":0,\"lastUpdated\":null,\"topEnvironments\":[],\"showProjects\":false,\"successfulCount\":0},\"byInstanceType\":{}},\"repository\":{\"overall\":{\"count\":0,\"lastUpdated\":null},\"byInstanceType\":{}},\"branch\":{\"overall\":{\"count\":0,\"lastUpdated\":null},\"byInstanceType\":{}}}},\"isStale\":false}}",
      "aggregateprogress": {
        "progress": 0,
        "total": 0
      },
      "priority": {
        "self": "https://jira.tidbcloud.com/rest/api/2/priority/2",
        "iconUrl": "https://jira.tidbcloud.com/images/icons/priorities/high.svg",
        "name": "High",
        "id": "2"
      },
      "customfield_10100": "0|i016lj:",
      "customfield_10101": null,
      "labels": [
        "JIRALERT{e46adb6c978d75693e4228732f6d6835d8af88d5c1c8911611ad7efdb4a208b9afd8ba5e9e5b2b578d6df5017bbf30683e7f78a999e4d0caeb4b7b45f2792de8}"
      ],
      "customfield_10400": null,
      "environment": null,
      "timeestimate": null,
      "aggregatetimeoriginalestimate": null,
      "duedate": null,
      "progress": {
        "progress": 0,
        "total": 0
      },
      "comment": {
        "comments": [],
        "maxResults": 0,
        "total": 0,
        "startAt": 0
      },
      "issuelinks": [],
      "votes": {
        "self": "https://jira.tidbcloud.com/rest/api/2/issue/TCA-106/votes",
        "votes": 0,
        "hasVoted": false
      },
      "worklog": {
        "startAt": 0,
        "maxResults": 20,
        "total": 0,
        "worklogs": []
      },
      "assignee": null,
      "updated": "2022-06-13T05:41:46.000+0000",
      "status": {
        "self": "https://jira.tidbcloud.com/rest/api/2/status/10308",
        "description": "",
        "iconUrl": "https://jira.tidbcloud.com/images/icons/status_generic.gif",
        "name": "To Do",
        "id": "10308",
        "statusCategory": {
          "self": "https://jira.tidbcloud.com/rest/api/2/statuscategory/2",
          "id": 2,
          "key": "new",
          "colorName": "blue-gray",
          "name": "To Do"
        }
      }
    }
  },
  "changelog": {
    "id": "62984",
    "items": [
      {
        "field": "description",
        "fieldtype": "jira",
        "from": null,
        "fromString": "Labels:\n - alertname = AwsSharedProviderTiDBClusterUnavailable\n - cluster = base/eks/us-west-2\n - component = aws-shared-provider\n - endpoint = metric\n - instance = 10.0.102.83:8080\n - job = dispatcher-metrics\n - kubernetes = prod-us-west-2-f01\n - namespace = prod-1372813089195411303\n - network = aws-free-tier-us-west-2\n - phase = Unavailable\n - pod = dispatcher-6cb88f8c98-lv9xr\n - prometheus = monitoring/k8s\n - provider = eks\n - provider_type = aws-free-tier\n - region = us-west-2\n - service = dispatcher-metrics\n - severity = critical\n - tidb = 1379661944615924074\n - type = infra\n\nAnnotations:\n - description = Cluster 1379661944615924074 under kubernetes prod-us-west-2-f01 is currently unavailable.\n\nSource: http://prometheus-k8s-0:9090/graph?g0.expr=dispatcher_cluster_status_phase%7Bphase%3D%22Unavailable%22%7D+%3D%3D+1&g0.tab=1\n",
        "to": null,
        "toString": "Labels:\n - alertname = AwsSharedProviderTiDBClusterUnavailable\n - cluster = base/eks/us-west-2\n - component = aws-shared-provider\n - endpoint = metric\n - instance = 10.0.102.83:8080\n - job = dispatcher-metrics\n - kubernetes = prod-us-west-2-f01\n - namespace = prod-1372813089195441284\n - network = aws-free-tier-us-west-2\n - phase = Unavailable\n - pod = dispatcher-6cb88f8c98-lv9xr\n - prometheus = monitoring/k8s\n - provider = eks\n - provider_type = aws-free-tier\n - region = us-west-2\n - service = dispatcher-metrics\n - severity = critical\n - tidb = 1379661944615924077\n - type = infra\n\nAnnotations:\n - description = Cluster 1379661944615924077 under kubernetes prod-us-west-2-f01 is currently unavailable.\n\nSource: http://prometheus-k8s-0:9090/graph?g0.expr=dispatcher_cluster_status_phase%7Bphase%3D%22Unavailable%22%7D+%3D%3D+1&g0.tab=1\n"
      }
    ]
  }
}
`

func TestCreateIssueFromInfo(t *testing.T) {
	var info JiraEvent
	err := json.Unmarshal([]byte(jsonStr), &info)
	if err != nil {
		t.Error(err)
	}
	issue, err := info.ToIssue()
	if err != nil {
		t.Error(err)
	}
	if issue.Key != "TCA-106" {
		t.Error("wrong issue")
	}
	fmt.Println(issue)
}
