package webhook

import (
	"encoding/json"
	"strings"

	"gitlab.com/Timfa/bluegit/internal/ci"
)

// Grenzen voor wat een webhook van een gefaalde job meestuurt.
const (
	LogMaxLines = 200
	LogMaxBytes = 64 << 10
)

// MaxPushCommits is het aantal commits in een push-payload.
// Dat zijn de nieuwste in het bereik, oudste eerst.
const MaxPushCommits = 20

// Document is de JSON-body van een webhook zonder eigen sjabloon.
type Document struct {
	ObjectKind string `json:"object_kind"`
	Type       string `json:"type"`
	EventName  string `json:"event_name"`
	Project    string `json:"project"`
	Group      string `json:"group,omitempty"`
	Actor      string `json:"actor,omitempty"`
	Summary    string `json:"summary,omitempty"`
	URL        string `json:"url,omitempty"`
	Branch     string `json:"branch,omitempty"`
	Commit     string `json:"commit,omitempty"`
	PipelineID string `json:"pipeline_id,omitempty"`
	ReleaseTag string `json:"release_tag,omitempty"`

	Pipeline *PipelineInfo `json:"pipeline,omitempty"`
	Jobs     *[]JobInfo    `json:"jobs,omitempty"`

	Ref     string        `json:"ref,omitempty"`
	Before  string        `json:"before,omitempty"`
	After   string        `json:"after,omitempty"`
	Commits *[]CommitInfo `json:"commits,omitempty"`

	MergeRequest *MRInfo `json:"merge_request,omitempty"`
	Comment      string  `json:"comment,omitempty"`

	Release *ReleaseInfo `json:"release,omitempty"`
	Issue   *IssueInfo   `json:"issue,omitempty"`
	Note    *NoteInfo    `json:"note,omitempty"`
}

// NoteInfo is een reactie op een issue of merge request.
type NoteInfo struct {
	Body         string `json:"body"`
	NoteableType string `json:"noteable_type"`
	NoteableID   int64  `json:"noteable_id"`
	Author       string `json:"author"`
	URL          string `json:"url"`
}

// PipelineInfo is de pipeline waar het event over gaat.
type PipelineInfo struct {
	ID            int64   `json:"id"`
	Status        string  `json:"status"`
	Ref           string  `json:"ref"`
	SHA           string  `json:"sha"`
	CommitMessage string  `json:"commit_message"`
	Author        string  `json:"author"`
	Duration      float64 `json:"duration"`
	URL           string  `json:"url,omitempty"`
}

// JobInfo is één job in een pipeline-event.
// Elke job stuurt de console-output mee. log_url staat er alleen als de log
// is afgekapt, en wijst naar de API voor de volledige tekst.
type JobInfo struct {
	Name         string  `json:"name"`
	Stage        string  `json:"stage"`
	Status       string  `json:"status"`
	Duration     float64 `json:"duration"`
	AllowFailure bool    `json:"allow_failure"`
	WebURL       string  `json:"web_url"`
	Log          string  `json:"log"`
	LogTruncated bool    `json:"log_truncated"`
	LogURL       string  `json:"log_url,omitempty"`
	// CancelReason is superseded (nieuwere pipeline) of manual bij status canceled.
	CancelReason string `json:"cancel_reason,omitempty"`
	// FailureReason is bijv. job_execution_timeout bij status failed.
	FailureReason string `json:"failure_reason,omitempty"`
}

// CommitInfo is één commit in een push of merge request.
// Files noemt de wijzigingen. De difftekst zelf staat niet in de payload;
// diff_url wijst naar de API die hem teruggeeft.
type CommitInfo struct {
	SHA       string       `json:"sha"`
	Message   string       `json:"message"`
	Author    string       `json:"author"`
	Timestamp string       `json:"timestamp"`
	URL       string       `json:"url"`
	Files     []FileChange `json:"files"`
	DiffURL   string       `json:"diff_url"`
}

// FileChange is één gewijzigd bestand, met status en regelaantallen.
// Status is added, modified, removed of renamed.
type FileChange struct {
	Path         string `json:"path"`
	Status       string `json:"status"`
	PreviousPath string `json:"previous_path,omitempty"`
	Additions    int    `json:"additions"`
	Deletions    int    `json:"deletions"`
	Binary       bool   `json:"binary,omitempty"`
}

// MRInfo is de merge request van het event.
// DiffStats is de three-dot vergelijking. De difftekst staat op diff_url.
type MRInfo struct {
	ID           int64          `json:"id"`
	Number       int64          `json:"number"`
	Title        string         `json:"title"`
	Description  string         `json:"description"`
	SourceBranch string         `json:"source_branch"`
	TargetBranch string         `json:"target_branch"`
	Status       string         `json:"status"`
	Author       string         `json:"author"`
	Action       string         `json:"action"`
	URL          string         `json:"url,omitempty"`
	Reviewers    []ReviewerInfo `json:"reviewers"`
	Comments     []CommentInfo  `json:"comments"`
	Commits      []CommitInfo   `json:"commits"`
	DiffStats    DiffStats      `json:"diff_stats"`
	DiffURL      string         `json:"diff_url"`
}

// ReviewerInfo is de huidige review van één persoon.
type ReviewerInfo struct {
	Username string `json:"username"`
	Status   string `json:"status"`
}

// CommentInfo is een reactie op de merge request.
type CommentInfo struct {
	ID        int64  `json:"id"`
	Author    string `json:"author"`
	Body      string `json:"body"`
	CreatedAt string `json:"created_at"`
	FilePath  string `json:"file_path,omitempty"`
	LineStart int    `json:"line_start,omitempty"`
	LineEnd   int    `json:"line_end,omitempty"`
	ParentID  int64  `json:"parent_id,omitempty"`
}

// DiffStats telt de regels van de vergelijking, per bestand.
type DiffStats struct {
	Additions int          `json:"additions"`
	Deletions int          `json:"deletions"`
	Files     []FileChange `json:"files"`
}

// IssueInfo is het issue van het event.
// Action is opened, updated, closed, reopened of commented.
type IssueInfo struct {
	ID           int64    `json:"id"`
	Number       int64    `json:"number"`
	Title        string   `json:"title"`
	Description  string   `json:"description"`
	Status       string   `json:"status"`
	Confidential bool     `json:"confidential"`
	Author       string   `json:"author"`
	Assignees    []string `json:"assignees"`
	Labels       []string `json:"labels"`
	Milestone    string   `json:"milestone"`
	DueDate      string   `json:"due_date"`
	Action       string   `json:"action"`
	URL          string   `json:"url,omitempty"`
}

// ReleaseInfo is een gepubliceerde release.
type ReleaseInfo struct {
	Tag    string      `json:"tag"`
	Name   string      `json:"name"`
	Commit string      `json:"commit"`
	Assets []AssetInfo `json:"assets"`
}

// AssetInfo is een bestand bij een release.
type AssetInfo struct {
	Name string `json:"name"`
	URL  string `json:"url"`
	Size int64  `json:"size"`
}

// Document bouwt de JSON-structuur. Lege deelobjecten blijven weg.
func (ev Event) Document() Document {
	d := Document{
		ObjectKind:   objectKind(ev.Type),
		Type:         ev.Type,
		Project:      ev.Project,
		Group:        ev.Group,
		Actor:        ev.Actor,
		Summary:      ev.Summary,
		URL:          ev.URL,
		Branch:       ev.Branch,
		Commit:       ev.Commit,
		PipelineID:   ev.PipelineID,
		ReleaseTag:   ev.ReleaseTag,
		Pipeline:     ev.Pipeline,
		Ref:          ev.Ref,
		Before:       ev.Before,
		After:        ev.After,
		MergeRequest: ev.MergeRequest,
		Release:      ev.Release,
		Issue:        ev.Issue,
	}
	d.EventName = Specific(ev)
	if d.EventName == "" {
		d.EventName = ev.Type
	}
	switch ev.Type {
	case EventPush:
		commits := ev.Commits
		if commits == nil {
			commits = []CommitInfo{}
		}
		for i := range commits {
			if commits[i].Files == nil {
				commits[i].Files = []FileChange{}
			}
		}
		d.Commits = &commits
	case EventPipelineSuccess, EventPipelineFailure:
		jobs := ev.Jobs
		if jobs == nil {
			jobs = []JobInfo{}
		}
		d.Jobs = &jobs
	case EventMergeRequest:
		if ev.MergeRequest != nil {
			mr := *ev.MergeRequest
			if mr.Number == 0 {
				mr.Number = mr.ID
			}
			if mr.Reviewers == nil {
				mr.Reviewers = []ReviewerInfo{}
			}
			if mr.Comments == nil {
				mr.Comments = []CommentInfo{}
			}
			if mr.Commits == nil {
				mr.Commits = []CommitInfo{}
			}
			for i := range mr.Commits {
				if mr.Commits[i].Files == nil {
					mr.Commits[i].Files = []FileChange{}
				}
			}
			if mr.DiffStats.Files == nil {
				mr.DiffStats.Files = []FileChange{}
			}
			d.MergeRequest = &mr
			if mr.Action == "commented" {
				d.Comment = ev.Comment
				d.Note = &NoteInfo{Body: ev.Comment, NoteableType: "MergeRequest", NoteableID: mr.ID, Author: ev.Actor, URL: firstNonEmpty(mr.URL, ev.URL)}
			}
		}
	case EventIssue:
		if ev.Issue != nil {
			iss := *ev.Issue
			if iss.Number == 0 {
				iss.Number = iss.ID
			}
			if iss.Assignees == nil {
				iss.Assignees = []string{}
			}
			if iss.Labels == nil {
				iss.Labels = []string{}
			}
			d.Issue = &iss
			if iss.Action == "commented" {
				d.Comment = ev.Comment
				d.Note = &NoteInfo{Body: ev.Comment, NoteableType: "Issue", NoteableID: iss.ID, Author: ev.Actor, URL: firstNonEmpty(iss.URL, ev.URL)}
			}
		}
	}
	if d.Release != nil && d.Release.Assets == nil {
		rel := *d.Release
		rel.Assets = []AssetInfo{}
		d.Release = &rel
	}
	return d
}

func objectKind(eventType string) string {
	switch eventType {
	case EventPipelineSuccess, EventPipelineFailure:
		return "pipeline"
	case EventRelease:
		return "release"
	case EventMergeRequest:
		return "merge_request"
	default:
		return eventType
	}
}

// TailLog houdt de laatste LogMaxLines regels en hoogstens LogMaxBytes.
// Geheimwaarden van minstens 8 tekens worden [MASKED], net als in de joblog.
// truncated is true zodra er regels of bytes af zijn.
func TailLog(text string, secrets []string) (string, bool) {
	text = ci.Mask(text, secrets)
	if text == "" {
		return "", false
	}
	truncated := false
	lines := strings.Split(text, "\n")
	if len(lines) > LogMaxLines {
		lines = lines[len(lines)-LogMaxLines:]
		truncated = true
	}
	out := strings.Join(lines, "\n")
	if len(out) > LogMaxBytes {
		out = cutUTF8Tail(out, LogMaxBytes)
		truncated = true
	}
	return out, truncated
}

func cutUTF8Tail(s string, max int) string {
	if len(s) <= max {
		return s
	}
	s = s[len(s)-max:]
	for len(s) > 0 && s[0]&0xC0 == 0x80 {
		s = s[1:]
	}
	return s
}

// Example is het voorbeeld op de infopagina.
func Example() string {
	samples := []Event{
		{
			Type: EventPipelineFailure, Project: "tim/app", Actor: "tim",
			Summary: "pipeline #26 voor tim/app is mislukt",
			URL:     "https://git.example/tim/app/-/pipelines/26",
			Branch:  "master", Commit: "725e6947", PipelineID: "26",
			Pipeline: &PipelineInfo{
				ID: 26, Status: "failed", Ref: "refs/heads/master", SHA: "725e6947",
				CommitMessage: "fix de build", Author: "tim", Duration: 12.4,
				URL: "https://git.example/tim/app/-/pipelines/26",
			},
			Jobs: []JobInfo{
				{
					Name: "test", Stage: "test", Status: "failed", Duration: 4.1,
					AllowFailure: false, WebURL: "https://git.example/tim/app/-/pipelines/26/jobs/7",
					Log: "go: token [MASKED]\nFAIL", LogTruncated: true,
					LogURL: "https://git.example/api/v1/repos/tim/app/jobs/7/log",
				},
				{
					Name: "build", Stage: "build", Status: "success", Duration: 8,
					WebURL: "https://git.example/tim/app/-/pipelines/26/jobs/8",
					Log:    "built bluegit",
				},
			},
		},
		{
			Type: EventPush, Project: "tim/app", Actor: "tim", Branch: "master",
			Ref: "refs/heads/master", Before: strings.Repeat("0", 40), After: "abc123",
			Commits: []CommitInfo{{
				SHA: "abc123", Message: "fix de build", Author: "Tim <tim@example.com>",
				Timestamp: "2026-10-22T12:00:00Z",
				URL:       "https://git.example/tim/app/-/commit/abc123",
				DiffURL:   "https://git.example/api/v1/repos/tim/app/commits/abc123/diff",
				Files: []FileChange{{
					Path: "README.md", Status: "modified", Additions: 1, Deletions: 1,
				}},
			}},
		},
		{
			Type: EventMergeRequest, Project: "tim/app", Actor: "ada",
			MergeRequest: &MRInfo{
				ID: 4, Title: "Toon de kloon-URL", Description: "SSH en HTTPS.",
				SourceBranch: "feature", TargetBranch: "master", Status: "open",
				Author: "ada", Action: "opened",
				URL:       "https://git.example/tim/app/-/merge-requests/4",
				DiffURL:   "https://git.example/api/v1/repos/tim/app/merge-requests/4/diff",
				Reviewers: []ReviewerInfo{{Username: "tim", Status: "approved"}},
				Comments:  []CommentInfo{},
				Commits: []CommitInfo{{
					SHA: "abc123", Message: "fix de build", Author: "Tim <tim@example.com>",
					Timestamp: "2026-10-22T12:00:00Z",
					URL:       "https://git.example/tim/app/-/commit/abc123",
					DiffURL:   "https://git.example/api/v1/repos/tim/app/commits/abc123/diff",
					Files:     []FileChange{{Path: "README.md", Status: "modified", Additions: 1, Deletions: 1}},
				}},
				DiffStats: DiffStats{
					Additions: 1, Deletions: 1,
					Files: []FileChange{{Path: "README.md", Status: "modified", Additions: 1, Deletions: 1}},
				},
			},
		},
		{
			Type: EventRelease, Project: "tim/app", ReleaseTag: "v1.2.0", Commit: "abc123",
			Release: &ReleaseInfo{
				Tag: "v1.2.0", Name: "BlueGit 1.2.0", Commit: "abc123",
				Assets: []AssetInfo{{
					Name: "bluegit", Size: 8123456,
					URL: "https://git.example/tim/app/-/releases/v1.2.0/assets/bluegit",
				}},
			},
		},
	}
	var b strings.Builder
	for i, ev := range samples {
		if i > 0 {
			b.WriteString("\n\n")
		}
		raw, err := json.MarshalIndent(ev.Document(), "", "  ")
		if err != nil {
			continue
		}
		b.Write(raw)
	}
	return b.String()
}

// IssueExample is het voorbeeld van een issue-event op de infopagina.
func IssueExample() string {
	ev := Event{
		Type: EventIssue, Project: "tim/app", Actor: "ada",
		Summary: "issue #12 opened: Inloggen faalt",
		URL:     "https://git.example/tim/app/-/issues/12",
		Issue: &IssueInfo{
			ID: 12, Title: "Inloggen faalt", Description: "Zie #3 en !4.",
			Status: "open", Confidential: false, Author: "ada",
			Assignees: []string{"tim"}, Labels: []string{"bug"},
			Milestone: "v1", DueDate: "2026-11-01", Action: "opened",
			URL: "https://git.example/tim/app/-/issues/12",
		},
	}
	raw, err := json.MarshalIndent(ev.Document(), "", "  ")
	if err != nil {
		return ""
	}
	return string(raw)
}

func firstNonEmpty(a, b string) string {
	if a != "" {
		return a
	}
	return b
}
