// Copyright Earl Warren <contact@earl-warren.org>
// Copyright Loïc Dachary <loic@dachary.org>
// SPDX-License-Identifier: MIT

package f3

import (
	"context"
	"time"
)

type PullRequestFetchFunc func(ctx context.Context, url, ref string)

const (
	PullRequestStateOpen   = "open"
	PullRequestStateClosed = "closed"
)

type PullRequest struct {
	Common
	PosterID       *Reference        `json:"poster_id"`
	Title          string            `json:"title"`
	Content        string            `json:"content"`
	Attachments    []*Attachment     `json:"attachments"`
	Milestone      *Reference        `json:"milestone"`
	State          string            `json:"state"` // open, closed
	IsLocked       bool              `json:"is_locked"`
	Created        time.Time         `json:"created"`
	Updated        time.Time         `json:"updated"`
	Closed         *time.Time        `json:"closed"`
	Merged         bool              `json:"merged"`
	MergedTime     *time.Time        `json:"merged_time"`
	MergeCommitSHA string            `json:"merged_commit_sha"`
	Head           PullRequestBranch `json:"head"`
	Base           PullRequestBranch `json:"base"`

	FetchFunc PullRequestFetchFunc `json:"-"`
}

func (o PullRequest) Equal(other PullRequest) bool {
	return o.Common.Equal(other.Common) &&
		nilOrEqual(o.PosterID, other.PosterID) &&
		o.Title == other.Title &&
		o.Content == other.Content &&
		arrayEqual(o.Attachments, other.Attachments) &&
		nilOrEqual(o.Milestone, other.Milestone) &&
		o.State == other.State &&
		o.IsLocked == other.IsLocked &&
		o.Merged == other.Merged &&
		nilOrEqual(o.MergedTime, other.MergedTime) &&
		o.MergeCommitSHA == other.MergeCommitSHA &&
		o.Head.Equal(other.Head) &&
		o.Base.Equal(other.Base)
}

func (o *PullRequest) GetReferences() References {
	references := o.Common.GetReferences()
	if !o.Milestone.IsNil() {
		references = append(references, o.Milestone)
	}
	references = append(references, o.Base.GetReferences()...)
	references = append(references, o.Head.GetReferences()...)
	return append(references, o.PosterID)
}

func (o *PullRequest) IsForkPullRequest() bool {
	return o.Head.Repository != o.Base.Repository
}

func (o *PullRequest) Clone() Interface {
	clone := &PullRequest{}
	*clone = *o
	return clone
}
