package server

import (
	"context"
	"math"
	"net/url"
	"strconv"
	"strings"
	"time"

	"gitlab.com/Timfa/bluegit/internal/gitrepo"
	"gitlab.com/Timfa/bluegit/internal/i18n"
	"gitlab.com/Timfa/bluegit/internal/store"
	"gitlab.com/Timfa/bluegit/internal/webhook"
)

// enrichEvent vult de details die de JSON-body van een webhook meestuurt.
func (s *Server) enrichEvent(ctx context.Context, repo store.Repo, ev webhook.Event) webhook.Event {
	switch ev.Type {
	case webhook.EventPipelineSuccess, webhook.EventPipelineFailure:
		s.fillPipelineEvent(ctx, repo, &ev)
	case webhook.EventPush:
		s.fillPushEvent(ctx, repo, &ev)
	}
	return ev
}

func (s *Server) fillPipelineEvent(ctx context.Context, repo store.Repo, ev *webhook.Event) {
	id, err := strconv.ParseInt(ev.PipelineID, 10, 64)
	if err != nil || id <= 0 || s.Store == nil {
		return
	}
	p, err := s.Store.PipelineByID(ctx, repo.ID, id)
	if err != nil {
		return
	}
	base := strings.TrimRight(s.Cfg.BaseURL, "/")
	pipeURL := base + "/" + repo.FullPath() + "/-/pipelines/" + strconv.FormatInt(p.ID, 10)
	if ev.URL == "" || !strings.HasPrefix(ev.URL, "http") {
		ev.URL = pipeURL
	}
	if ev.Commit == "" {
		ev.Commit = p.CommitSHA
	}
	if ev.Branch == "" {
		ev.Branch = refName(p.Ref)
	}
	if ev.Actor == "" {
		ev.Actor = p.Actor
	}
	msg := p.CommitTitle
	author := p.Actor
	if s.Git != "" && s.StoragePath() != "" && p.CommitSHA != "" {
		dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
		if c, err := gitrepo.Show(ctx, s.Git, dir, p.CommitSHA); err == nil && c.SHA != "" {
			if text := commitText(c); text != "" {
				msg = text
			}
			if author == "" {
				author = commitAuthor(c)
			}
		}
	}
	ev.PipelineID = strconv.FormatInt(p.ID, 10)
	ev.Pipeline = &webhook.PipelineInfo{
		ID: p.ID, Status: p.Status, Ref: p.Ref, SHA: p.CommitSHA,
		CommitMessage: msg, Author: author, Duration: elapsedSeconds(p.StartedAt, p.FinishedAt),
		URL: pipeURL,
	}
	jobs, err := s.Store.JobsByPipeline(ctx, p.ID)
	if err != nil {
		return
	}
	secrets := s.maskSecrets(ctx, repo)
	ev.Jobs = make([]webhook.JobInfo, 0, len(jobs))
	for _, j := range jobs {
		info := webhook.JobInfo{
			Name: j.Name, Stage: j.Stage, Status: j.Status,
			Duration:     elapsedSeconds(j.StartedAt, j.FinishedAt),
			AllowFailure: j.AllowFailure,
			WebURL:       pipeURL + "/jobs/" + strconv.FormatInt(j.ID, 10),
		}
		if j.Status == "failed" {
			log, truncated := webhook.TailLog(j.Log, secrets)
			info.Log = log
			info.LogTruncated = &truncated
			info.LogURL = info.WebURL + "/log?raw=1"
		}
		ev.Jobs = append(ev.Jobs, info)
	}
}

func (s *Server) fillPushEvent(ctx context.Context, repo store.Repo, ev *webhook.Event) {
	if ev.Commits != nil || s.Git == "" || s.StoragePath() == "" || ev.After == "" {
		if ev.Commits == nil {
			ev.Commits = []webhook.CommitInfo{}
		}
		return
	}
	dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
	list, err := gitrepo.RangeLog(ctx, s.Git, dir, ev.Before, ev.After)
	if err != nil || len(list) == 0 {
		ev.Commits = []webhook.CommitInfo{}
		return
	}
	if len(list) > webhook.MaxPushCommits {
		list = list[:webhook.MaxPushCommits]
	}
	base := strings.TrimRight(s.Cfg.BaseURL, "/")
	ev.Commits = make([]webhook.CommitInfo, 0, len(list))
	for i := len(list) - 1; i >= 0; i-- {
		c := list[i]
		ev.Commits = append(ev.Commits, webhook.CommitInfo{
			SHA: c.SHA, Message: commitText(c), Author: commitAuthor(c),
			URL: base + "/" + repo.FullPath() + "/-/commit/" + c.SHA,
		})
	}
}

func (s *Server) maskSecrets(ctx context.Context, repo store.Repo) []string {
	if s.Store == nil {
		return nil
	}
	var out []string
	add := func(kind string, id int64) {
		vals, err := s.Store.SecretValues(ctx, kind, id, true)
		if err != nil {
			return
		}
		for _, v := range vals {
			out = append(out, v)
		}
	}
	add("repo", repo.ID)
	if repo.OwnerKind == "group" {
		add("group", repo.OwnerID)
	}
	return out
}

func (s *Server) mrEvent(repo store.Repo, mr store.MergeRequest, actor, action, comment string) webhook.Event {
	num := strconv.FormatInt(mr.Number, 10)
	path := strings.TrimRight(s.Cfg.BaseURL, "/") + repoURL(repo) + "/-/merge-requests/" + num
	summary := i18n.T(i18n.EN, "hook.mr", num, mr.Title)
	switch action {
	case "merged":
		summary = i18n.T(i18n.EN, "hook.mrMerged", num, mr.Title)
	case "commented":
		summary = i18n.T(i18n.EN, "hook.mrComment", num)
	}
	return webhook.Event{
		Type:    webhook.EventMergeRequest,
		Project: repo.FullPath(),
		Branch:  mr.TargetBranch,
		Actor:   actor,
		Summary: summary,
		URL:     path,
		Comment: comment,
		MergeRequest: &webhook.MRInfo{
			ID: mr.Number, Title: mr.Title, Description: mr.Description,
			SourceBranch: mr.SourceBranch, TargetBranch: mr.TargetBranch,
			Status: mr.Status, Author: mr.Author, Action: action, URL: path,
		},
	}
}

func (s *Server) mrHook(repo store.Repo, mr store.MergeRequest, actor, action, comment string) {
	s.Dispatch(repo.ID, s.mrEvent(repo, mr, actor, action, comment))
}

func (s *Server) releaseEvent(repo store.Repo, tag, name, commit string, assets []store.ReleaseAsset) webhook.Event {
	base := strings.TrimRight(s.Cfg.BaseURL, "/")
	page := base + repoURL(repo) + "/-/releases"
	list := make([]webhook.AssetInfo, 0, len(assets))
	for _, a := range assets {
		list = append(list, webhook.AssetInfo{
			Name: a.Name, Size: a.Size,
			URL: base + repoURL(repo) + "/-/releases/" + url.PathEscape(tag) + "/assets/" + url.PathEscape(a.Name),
		})
	}
	return webhook.Event{
		Type: webhook.EventRelease, Project: repo.FullPath(), Commit: commit,
		ReleaseTag: tag, Summary: i18n.T(i18n.EN, "hook.release", tag, repo.FullPath()),
		URL:     page,
		Release: &webhook.ReleaseInfo{Tag: tag, Name: name, Commit: commit, Assets: list},
	}
}

func refName(ref string) string {
	if b, ok := gitrepo.BranchOfRef(ref); ok {
		return b
	}
	if name, ok := strings.CutPrefix(ref, "refs/tags/"); ok && name != "" {
		return name
	}
	return ref
}

func commitText(c gitrepo.Commit) string {
	if c.Subject == "" {
		return strings.TrimSpace(c.Body)
	}
	if strings.TrimSpace(c.Body) == "" {
		return c.Subject
	}
	return c.Subject + "\n\n" + strings.TrimSpace(c.Body)
}

func commitAuthor(c gitrepo.Commit) string {
	name := strings.TrimSpace(c.Author)
	email := strings.TrimSpace(c.Email)
	switch {
	case name == "":
		return email
	case email == "":
		return name
	default:
		return name + " <" + email + ">"
	}
}

func elapsedSeconds(start, end time.Time) float64 {
	if start.IsZero() || end.IsZero() || end.Before(start) {
		return 0
	}
	return math.Round(end.Sub(start).Seconds()*1000) / 1000
}
