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"`
	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"`
}

// 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"`
}

// 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"`
	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"`
}

// 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,
	}
	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.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
			}
		}
	}
	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()
}
