// Copyright 2013 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package github

import (
	"context"
	"fmt"
	"time"
)

// IssuesService handles communication with the issue related
// methods of the GitHub API.
//
// GitHub API docs: https://docs.github.com/rest/issues?apiVersion=2022-11-28
type IssuesService service

// Issue represents a GitHub issue on a repository.
//
// Note: As far as the GitHub API is concerned, every pull request is an issue,
// but not every issue is a pull request. Some endpoints, events, and webhooks
// may also return pull requests via this struct. If PullRequestLinks is nil,
// this is an issue, and if PullRequestLinks is not nil, this is a pull request.
// The IsPullRequest helper method can be used to check that.
type Issue struct {
	ID     *int64  `json:"id,omitempty"`
	Number *int    `json:"number,omitempty"`
	State  *string `json:"state,omitempty"`
	// StateReason can be one of: "completed", "not_planned", "reopened".
	StateReason *string `json:"state_reason,omitempty"`
	Locked      *bool   `json:"locked,omitempty"`
	Title       *string `json:"title,omitempty"`
	Body        *string `json:"body,omitempty"`
	// AuthorAssociation is the issue author's relationship to the repository.
	// Possible values are "COLLABORATOR", "CONTRIBUTOR", "FIRST_TIMER", "FIRST_TIME_CONTRIBUTOR", "MEMBER", "OWNER", or "NONE".
	//
	// Deprecated: GitHub will remove this field from Events API payloads on October 7, 2025.
	// Use the Issues REST API endpoint to retrieve this information.
	// See: https://docs.github.com/rest/issues/issues?apiVersion=2022-11-28#get-an-issue
	AuthorAssociation *string            `json:"author_association,omitempty"`
	User              *User              `json:"user,omitempty"`
	Labels            []*Label           `json:"labels,omitempty"`
	Assignee          *User              `json:"assignee,omitempty"`
	Comments          *int               `json:"comments,omitempty"`
	ClosedAt          *Timestamp         `json:"closed_at,omitempty"`
	CreatedAt         *Timestamp         `json:"created_at,omitempty"`
	UpdatedAt         *Timestamp         `json:"updated_at,omitempty"`
	ClosedBy          *User              `json:"closed_by,omitempty"`
	URL               *string            `json:"url,omitempty"`
	HTMLURL           *string            `json:"html_url,omitempty"`
	CommentsURL       *string            `json:"comments_url,omitempty"`
	EventsURL         *string            `json:"events_url,omitempty"`
	LabelsURL         *string            `json:"labels_url,omitempty"`
	RepositoryURL     *string            `json:"repository_url,omitempty"`
	ParentIssueURL    *string            `json:"parent_issue_url,omitempty"`
	Milestone         *Milestone         `json:"milestone,omitempty"`
	PullRequestLinks  *PullRequestLinks  `json:"pull_request,omitempty"`
	Repository        *Repository        `json:"repository,omitempty"`
	Reactions         *Reactions         `json:"reactions,omitempty"`
	Assignees         []*User            `json:"assignees,omitempty"`
	NodeID            *string            `json:"node_id,omitempty"`
	Draft             *bool              `json:"draft,omitempty"`
	Type              *IssueType         `json:"type,omitempty"`
	IssueFieldValues  []*IssueFieldValue `json:"issue_field_values,omitempty"`

	// TextMatches is only populated from search results that request text matches
	// See: search.go and https://docs.github.com/rest/search/#text-match-metadata
	TextMatches []*TextMatch `json:"text_matches,omitempty"`

	// ActiveLockReason is populated only when LockReason is provided while locking the issue.
	// Possible values are: "off-topic", "too heated", "resolved", and "spam".
	ActiveLockReason *string `json:"active_lock_reason,omitempty"`
}

func (i Issue) String() string {
	return Stringify(i)
}

// IsPullRequest reports whether the issue is also a pull request. It uses the
// method recommended by GitHub's API documentation, which is to check whether
// PullRequestLinks is non-nil.
func (i Issue) IsPullRequest() bool {
	return i.PullRequestLinks != nil
}

// IssueRequest represents a request to create/edit an issue.
// It is separate from Issue above because otherwise Labels
// and Assignee fail to serialize to the correct JSON.
type IssueRequest struct {
	Title    *string   `json:"title,omitempty"`
	Body     *string   `json:"body,omitempty"`
	Labels   *[]string `json:"labels,omitempty"`
	Assignee *string   `json:"assignee,omitempty"`
	State    *string   `json:"state,omitempty"`
	// StateReason can be 'completed' or 'not_planned'.
	StateReason      *string                   `json:"state_reason,omitempty"`
	Milestone        *int                      `json:"milestone,omitempty"`
	Assignees        *[]string                 `json:"assignees,omitempty"`
	Type             *string                   `json:"type,omitempty"`
	IssueFieldValues []*IssueRequestFieldValue `json:"issue_field_values,omitempty"`
}

// PullRequestLinks object is added to the Issue object when it's an issue included
// in the IssueCommentEvent webhook payload, if the webhook is fired by a comment on a PR.
type PullRequestLinks struct {
	URL      *string    `json:"url,omitempty"`
	HTMLURL  *string    `json:"html_url,omitempty"`
	DiffURL  *string    `json:"diff_url,omitempty"`
	PatchURL *string    `json:"patch_url,omitempty"`
	MergedAt *Timestamp `json:"merged_at,omitempty"`
}

// IssueType represents the type of issue.
// For now it shows up when receiving an Issue event.
type IssueType struct {
	ID          *int64     `json:"id,omitempty"`
	NodeID      *string    `json:"node_id,omitempty"`
	Name        *string    `json:"name,omitempty"`
	Description *string    `json:"description,omitempty"`
	Color       *string    `json:"color,omitempty"`
	CreatedAt   *Timestamp `json:"created_at,omitempty"`
	UpdatedAt   *Timestamp `json:"updated_at,omitempty"`
}

// IssueFieldValueSingleSelectOption represents a single-select option for an issue field value.
//
// GitHub API docs: https://docs.github.com/rest/issues/issues?apiVersion=2022-11-28#get-an-issue
type IssueFieldValueSingleSelectOption struct {
	ID    int64  `json:"id"`
	Name  string `json:"name"`
	Color string `json:"color"`
}

// IssueRequestFieldValue represents a custom field value to set on an issue.
//
// GitHub API docs: https://docs.github.com/rest/issues/issues?apiVersion=2022-11-28#update-an-issue
type IssueRequestFieldValue struct {
	FieldID int64 `json:"field_id"`
	Value   any   `json:"value"`
}

// IssueFieldValue represents a custom field value attached to an issue.
// The Value field contains a string for text, single_select, and date fields,
// or a number for numeric fields.
//
// GitHub API docs: https://docs.github.com/rest/issues/issues?apiVersion=2022-11-28#get-an-issue
type IssueFieldValue struct {
	IssueFieldID       int64                              `json:"issue_field_id"`
	NodeID             string                             `json:"node_id"`
	DataType           string                             `json:"data_type"`
	Value              any                                `json:"value"`
	SingleSelectOption *IssueFieldValueSingleSelectOption `json:"single_select_option,omitempty"`
}

// ListAllIssuesOptions specifies the optional parameters to the
// IssuesService.ListAllIssues method.
type ListAllIssuesOptions struct {
	// Filter specifies which issues to list. Possible values are: assigned,
	// created, mentioned, subscribed, repos, all. Default is "assigned".
	Filter string `url:"filter,omitempty"`

	// State filters issues based on their state. Possible values are: open,
	// closed, all. Default is "open".
	State string `url:"state,omitempty"`

	// Labels filters issues based on their label.
	Labels []string `url:"labels,comma,omitempty"`

	// Sort specifies how to sort issues. Possible values are: created, updated,
	// and comments. Default value is "created".
	Sort string `url:"sort,omitempty"`

	// Direction in which to sort issues. Possible values are: asc, desc.
	// Default is "desc".
	Direction string `url:"direction,omitempty"`

	// Since filters issues by time.
	Since time.Time `url:"since,omitempty"`

	Collab bool `url:"collab,omitempty"`
	Orgs   bool `url:"orgs,omitempty"`
	Owned  bool `url:"owned,omitempty"`
	Pulls  bool `url:"pulls,omitempty"`

	ListOptions
}

// ListAllIssues gets issues assigned to the authenticated user across all visible repositories including owned repositories,
// member repositories, and organization repositories.
// You can use the filter query parameter to fetch issues that are not necessarily assigned to you.
//
// GitHub API docs: https://docs.github.com/rest/issues/issues?apiVersion=2022-11-28#list-issues-assigned-to-the-authenticated-user
//
//meta:operation GET /issues
func (s *IssuesService) ListAllIssues(ctx context.Context, opts *ListAllIssuesOptions) ([]*Issue, *Response, error) {
	u := "issues"
	u, err := addOptions(u, opts)
	if err != nil {
		return nil, nil, err
	}

	req, err := s.client.NewRequest(ctx, "GET", u, nil)
	if err != nil {
		return nil, nil, err
	}

	req.Header.Set("Accept", mediaTypeReactionsPreview)

	var issues []*Issue
	resp, err := s.client.Do(req, &issues)
	if err != nil {
		return nil, resp, err
	}

	return issues, resp, nil
}

// ListUserIssuesOptions specifies the optional parameters to the
// IssuesService.ListUserIssues method.
type ListUserIssuesOptions struct {
	// Filter specifies which issues to list. Possible values are: assigned,
	// created, mentioned, subscribed, repos, all. Default is "assigned".
	Filter string `url:"filter,omitempty"`

	// State filters issues based on their state. Possible values are: open,
	// closed, all. Default is "open".
	State string `url:"state,omitempty"`

	// Labels filters issues based on their label.
	Labels []string `url:"labels,comma,omitempty"`

	// Sort specifies how to sort issues. Possible values are: created, updated,
	// and comments. Default value is "created".
	Sort string `url:"sort,omitempty"`

	// Direction in which to sort issues. Possible values are: asc, desc.
	// Default is "desc".
	Direction string `url:"direction,omitempty"`

	// Since filters issues by time.
	Since time.Time `url:"since,omitempty"`

	ListOptions
}

// ListUserIssues gets issues across owned and member repositories assigned to the authenticated user.
//
// GitHub API docs: https://docs.github.com/rest/issues/issues?apiVersion=2022-11-28#list-user-account-issues-assigned-to-the-authenticated-user
//
//meta:operation GET /user/issues
func (s *IssuesService) ListUserIssues(ctx context.Context, opts *ListUserIssuesOptions) ([]*Issue, *Response, error) {
	u := "user/issues"
	u, err := addOptions(u, opts)
	if err != nil {
		return nil, nil, err
	}

	req, err := s.client.NewRequest(ctx, "GET", u, nil)
	if err != nil {
		return nil, nil, err
	}

	req.Header.Set("Accept", mediaTypeReactionsPreview)

	var issues []*Issue
	resp, err := s.client.Do(req, &issues)
	if err != nil {
		return nil, resp, err
	}

	return issues, resp, nil
}

// IssueListByOrgOptions specifies the optional parameters to the
// IssuesService.ListByOrg method.
type IssueListByOrgOptions struct {
	// Filter specifies which issues to list. Possible values are: assigned,
	// created, mentioned, subscribed, repos, all. Default is "assigned".
	Filter string `url:"filter,omitempty"`

	// State filters issues based on their state. Possible values are: open,
	// closed, all. Default is "open".
	State string `url:"state,omitempty"`

	// Labels filters issues based on their label.
	Labels []string `url:"labels,comma,omitempty"`

	// Type can be the name of an issue type.
	Type string `url:"type,omitempty"`

	// Sort specifies how to sort issues. Possible values are: created, updated,
	// and comments. Default value is "created".
	Sort string `url:"sort,omitempty"`

	// Direction in which to sort issues. Possible values are: asc, desc.
	// Default is "desc".
	Direction string `url:"direction,omitempty"`

	// Since filters issues by time.
	Since time.Time `url:"since,omitempty"`

	ListOptions
}

// ListByOrg fetches the issues in the specified organization for the
// authenticated user.
//
// GitHub API docs: https://docs.github.com/rest/issues/issues?apiVersion=2022-11-28#list-organization-issues-assigned-to-the-authenticated-user
//
//meta:operation GET /orgs/{org}/issues
func (s *IssuesService) ListByOrg(ctx context.Context, org string, opts *IssueListByOrgOptions) ([]*Issue, *Response, error) {
	u := fmt.Sprintf("orgs/%v/issues", org)
	u, err := addOptions(u, opts)
	if err != nil {
		return nil, nil, err
	}

	req, err := s.client.NewRequest(ctx, "GET", u, nil)
	if err != nil {
		return nil, nil, err
	}

	req.Header.Set("Accept", mediaTypeReactionsPreview)

	var issues []*Issue
	resp, err := s.client.Do(req, &issues)
	if err != nil {
		return nil, resp, err
	}

	return issues, resp, nil
}

// IssueListByRepoOptions specifies the optional parameters to the
// IssuesService.ListByRepo method.
type IssueListByRepoOptions struct {
	// Milestone limits issues for the specified milestone. Possible values are
	// a milestone number, "none" for issues with no milestone, "*" for issues
	// with any milestone.
	Milestone string `url:"milestone,omitempty"`

	// State filters issues based on their state. Possible values are: open,
	// closed, all. Default is "open".
	State string `url:"state,omitempty"`

	// Assignee filters issues based on their assignee. Possible values are a
	// user name, "none" for issues that are not assigned, "*" for issues with
	// any assigned user.
	Assignee string `url:"assignee,omitempty"`

	// Type can be the name of an issue type.
	// If the string * is passed, issues with any type are accepted.
	// If the string none is passed, issues without type are returned.
	Type string `url:"type,omitempty"`

	// Creator filters issues based on their creator.
	Creator string `url:"creator,omitempty"`

	// Mentioned filters issues to those mentioned a specific user.
	Mentioned string `url:"mentioned,omitempty"`

	// Labels filters issues based on their label.
	Labels []string `url:"labels,omitempty,comma"`

	// Sort specifies how to sort issues. Possible values are: created, updated,
	// and comments. Default value is "created".
	Sort string `url:"sort,omitempty"`

	// Direction in which to sort issues. Possible values are: asc, desc.
	// Default is "desc".
	Direction string `url:"direction,omitempty"`

	// Since filters issues by time.
	Since time.Time `url:"since,omitempty"`

	// ListCursorOptions specifies the optional parameters for cursor pagination.
	ListCursorOptions

	// Add ListOptions so offset pagination with integer type "page" query parameter is accepted
	// since ListCursorOptions accepts "page" as string only.
	ListOptions
}

// ListByRepo lists the issues for the specified repository.
//
// GitHub API docs: https://docs.github.com/rest/issues/issues?apiVersion=2022-11-28#list-repository-issues
//
//meta:operation GET /repos/{owner}/{repo}/issues
func (s *IssuesService) ListByRepo(ctx context.Context, owner, repo string, opts *IssueListByRepoOptions) ([]*Issue, *Response, error) {
	u := fmt.Sprintf("repos/%v/%v/issues", owner, repo)
	u, err := addOptions(u, opts)
	if err != nil {
		return nil, nil, err
	}

	req, err := s.client.NewRequest(ctx, "GET", u, nil)
	if err != nil {
		return nil, nil, err
	}

	req.Header.Set("Accept", mediaTypeReactionsPreview)

	var issues []*Issue
	resp, err := s.client.Do(req, &issues)
	if err != nil {
		return nil, resp, err
	}

	return issues, resp, nil
}

// Get a single issue.
//
// GitHub API docs: https://docs.github.com/rest/issues/issues?apiVersion=2022-11-28#get-an-issue
//
//meta:operation GET /repos/{owner}/{repo}/issues/{issue_number}
func (s *IssuesService) Get(ctx context.Context, owner, repo string, number int) (*Issue, *Response, error) {
	u := fmt.Sprintf("repos/%v/%v/issues/%v", owner, repo, number)
	req, err := s.client.NewRequest(ctx, "GET", u, nil)
	if err != nil {
		return nil, nil, err
	}

	req.Header.Set("Accept", mediaTypeReactionsPreview)

	var issue *Issue
	resp, err := s.client.Do(req, &issue)
	if err != nil {
		return nil, resp, err
	}

	return issue, resp, nil
}

// Create a new issue on the specified repository.
//
// GitHub API docs: https://docs.github.com/rest/issues/issues?apiVersion=2022-11-28#create-an-issue
//
//meta:operation POST /repos/{owner}/{repo}/issues
func (s *IssuesService) Create(ctx context.Context, owner, repo string, issue *IssueRequest) (*Issue, *Response, error) {
	u := fmt.Sprintf("repos/%v/%v/issues", owner, repo)
	req, err := s.client.NewRequest(ctx, "POST", u, issue)
	if err != nil {
		return nil, nil, err
	}

	var i *Issue
	resp, err := s.client.Do(req, &i)
	if err != nil {
		return nil, resp, err
	}

	return i, resp, nil
}

// Edit (update) an issue.
//
// GitHub API docs: https://docs.github.com/rest/issues/issues?apiVersion=2022-11-28#update-an-issue
//
//meta:operation PATCH /repos/{owner}/{repo}/issues/{issue_number}
func (s *IssuesService) Edit(ctx context.Context, owner, repo string, number int, issue *IssueRequest) (*Issue, *Response, error) {
	u := fmt.Sprintf("repos/%v/%v/issues/%v", owner, repo, number)
	req, err := s.client.NewRequest(ctx, "PATCH", u, issue)
	if err != nil {
		return nil, nil, err
	}

	var i *Issue
	resp, err := s.client.Do(req, &i)
	if err != nil {
		return nil, resp, err
	}

	return i, resp, nil
}

// RemoveMilestone removes a milestone from an issue.
//
// This is a helper method to explicitly update an issue with a `null` milestone, thereby removing it.
//
// GitHub API docs: https://docs.github.com/rest/issues/issues?apiVersion=2022-11-28#update-an-issue
//
//meta:operation PATCH /repos/{owner}/{repo}/issues/{issue_number}
func (s *IssuesService) RemoveMilestone(ctx context.Context, owner, repo string, issueNumber int) (*Issue, *Response, error) {
	u := fmt.Sprintf("repos/%v/%v/issues/%v", owner, repo, issueNumber)
	req, err := s.client.NewRequest(ctx, "PATCH", u, &struct {
		Milestone *Milestone `json:"milestone"`
	}{})
	if err != nil {
		return nil, nil, err
	}

	var i *Issue
	resp, err := s.client.Do(req, &i)
	if err != nil {
		return nil, resp, err
	}

	return i, resp, nil
}

// LockIssueOptions specifies the optional parameters to the
// IssuesService.Lock method.
type LockIssueOptions struct {
	// LockReason specifies the reason to lock this issue.
	// Providing a lock reason can help make it clearer to contributors why an issue
	// was locked. Possible values are: "off-topic", "too heated", "resolved", and "spam".
	LockReason string `json:"lock_reason,omitempty"`
}

// Lock an issue's conversation.
//
// GitHub API docs: https://docs.github.com/rest/issues/issues?apiVersion=2022-11-28#lock-an-issue
//
//meta:operation PUT /repos/{owner}/{repo}/issues/{issue_number}/lock
func (s *IssuesService) Lock(ctx context.Context, owner, repo string, number int, opts *LockIssueOptions) (*Response, error) {
	u := fmt.Sprintf("repos/%v/%v/issues/%v/lock", owner, repo, number)
	req, err := s.client.NewRequest(ctx, "PUT", u, opts)
	if err != nil {
		return nil, err
	}

	return s.client.Do(req, nil)
}

// Unlock an issue's conversation.
//
// GitHub API docs: https://docs.github.com/rest/issues/issues?apiVersion=2022-11-28#unlock-an-issue
//
//meta:operation DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock
func (s *IssuesService) Unlock(ctx context.Context, owner, repo string, number int) (*Response, error) {
	u := fmt.Sprintf("repos/%v/%v/issues/%v/lock", owner, repo, number)
	req, err := s.client.NewRequest(ctx, "DELETE", u, nil)
	if err != nil {
		return nil, err
	}

	return s.client.Do(req, nil)
}
