package jira

import (
	"strings"
	"time"

	"github.com/tidbcloud/jiraport/pkg/entity"

	jira "github.com/andygrunwald/go-jira"
)

type JiraWebhookEvent struct {
	IssueEventTypeName string          `json:"issue_event_type_name"`
	WebhookEvent       string          `json:"webhookEvent"`
	User               jira.User       `json:"user"`
	Issue              entity.RawIssue `json:"issue"`
	Changelog          struct {
		ID    string                `json:"id"`
		Items []jira.ChangelogItems `json:"items"`
	} `json:"changelog"`
	Timestamp int64 `json:"timestamp"`
}

func (info *JiraWebhookEvent) ToIssue() (*entity.Issue, error) {
	issue := &entity.Issue{
		Key:             info.Issue.Key,
		URL:             info.Issue.Self,
		RawIssue:        info.Issue,
		ReceivedVersion: info.Timestamp,
	}

	changelog := jira.Changelog{Histories: []jira.ChangelogHistory{{Items: info.Changelog.Items}}}

	issue.RawIssue.Changelog = &changelog

	fields := info.Issue.Fields

	if fields != nil {
		component := make([]string, 0, len(fields.Components))
		for i := range fields.Components {
			component = append(component, fields.Components[i].Name)
		}
		componentStr := strings.Join(component, ",")

		issue.Summary = fields.Summary
		issue.Description = fields.Description
		issue.CreateTime = time.Time(fields.Created)
		issue.Component = componentStr

		if fields.Reporter != nil {
			issue.ReporterEmail = fields.Reporter.EmailAddress
		}
		if fields.Assignee != nil {
			issue.AssigneeEmail = fields.Assignee.EmailAddress
		}
		if fields.Priority != nil {
			issue.Priority = fields.Priority.Name
		}
		if fields.Status != nil {
			issue.Status = fields.Status.Name
		}
	}
	return issue, nil
}
