package server

import (
	"bytes"
	"context"
	"io"
	"net/http"
	"net/url"
	"os/exec"
	"strings"
	"time"

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

func (s *Server) AfterPush(repo store.Repo, user store.User, before, after map[string]string) {
	if after == nil {
		return
	}
	actor := user.Username
	for ref, sha := range after {
		if before[ref] == sha {
			continue
		}
		if isZero(sha) {
			continue
		}
		if strings.HasPrefix(ref, "refs/tags/") {
			s.startPipeline(context.Background(), repo, sha, ref, actor, "push", before[ref], nil)
			continue
		}
		branch, ok := gitrepo.BranchOfRef(ref)
		if !ok {
			continue
		}
		s.recordPushContributions(repo, user, map[string]string{ref: before[ref]}, map[string]string{ref: sha})
		s.startPipeline(context.Background(), repo, sha, ref, actor, "push", before[ref], nil)
		s.startMergeRequestPipelines(context.Background(), repo, sha, branch, actor, before[ref])
		s.rerunMergeRequestsOnTarget(context.Background(), repo, branch, actor)
		web := strings.TrimRight(s.Cfg.BaseURL, "/") + "/" + repo.FullPath()
		s.Dispatch(repo.ID, webhook.Event{
			Type:    webhook.EventPush,
			Project: repo.FullPath(),
			Branch:  branch,
			Commit:  sha,
			Summary: i18n.T(i18n.EN, "hook.push", actor, branch, repo.FullPath()),
			URL:     web,
			Actor:   actor,
		})
	}
}

func isZero(sha string) bool {
	return strings.Trim(sha, "0") == ""
}

func (s *Server) startPipeline(ctx context.Context, repo store.Repo, sha, ref, actor, source, before string, mr *ci.MRInfo) int64 {
	if !s.Cfg.CI.Enabled || s.StoragePath() == "" {
		return 0
	}
	title, jobs, broken := s.planPipeline(ctx, repo, sha, ref, source, before, mr)
	if broken != nil {
		id, err := s.Store.RecordConfigFailure(ctx, repo.ID, sha, ref, broken.Error())
		if err != nil && s.Log != nil {
			s.Log.Error("pipeline", "err", err)
		}
		if mr != nil && id != 0 {
			_ = s.Store.AttachPipelineMR(ctx, id, mr.ID)
		}
		if id != 0 {
			s.cancelOlder(ctx, repo.ID, ref, id)
		}
		return id
	}
	if len(jobs) == 0 {
		return 0
	}
	id, err := s.Store.CreatePipeline(ctx, repo.ID, sha, ref, source, actor, title, jobs)
	if err != nil {
		if s.Log != nil {
			s.Log.Error("pipeline", "err", err)
		}
		return 0
	}
	if mr != nil {
		_ = s.Store.AttachPipelineMR(ctx, id, mr.ID)
	}
	s.cancelOlder(ctx, repo.ID, ref, id)
	return id
}

func (s *Server) cancelOlder(ctx context.Context, repoID int64, ref string, keep int64) {
	running, pipes, err := s.Store.CancelInterruptible(ctx, repoID, ref, keep)
	if err != nil {
		if s.Log != nil {
			s.Log.Error("interruptible", "err", err)
		}
		return
	}
	if s.Runner != nil {
		s.Runner.Interrupt(running)
	}
	for _, id := range pipes {
		if _, err := s.Store.RefreshPipelineStatus(ctx, id); err != nil && s.Log != nil {
			s.Log.Error("pipelinestatus", "err", err)
		}
	}
}

func gitOne(ctx context.Context, gitBin, dir string, args ...string) string {
	out, err := exec.CommandContext(ctx, gitBin, append([]string{"-C", dir}, args...)...).Output()
	if err != nil {
		return ""
	}
	return strings.TrimSpace(string(out))
}

func gitLines(ctx context.Context, gitBin, dir string, args ...string) []string {
	out := gitOne(ctx, gitBin, dir, args...)
	if out == "" {
		return []string{}
	}
	return strings.Split(out, "\n")
}

func changedFiles(ctx context.Context, gitBin, dir, sha, before string, all []string) []string {
	if before == "" || strings.Trim(before, "0") == "" {
		parent := gitOne(ctx, gitBin, dir, "rev-parse", "--verify", sha+"^")
		if parent == "" {
			return all
		}
		before = parent
	}
	out, err := exec.CommandContext(ctx, gitBin, "-C", dir, "diff", "--name-only", before, sha).Output()
	if err != nil {
		return nil
	}
	text := strings.TrimSpace(string(out))
	if text == "" {
		return []string{}
	}
	return strings.Split(text, "\n")
}

func pushEvent(repo store.Repo, kind, branch, commit, actor, summary, path string) webhook.Event {
	return webhook.Event{
		Type: kind, Project: repo.FullPath(), Branch: branch, Commit: commit,
		Actor: actor, Summary: summary, URL: path,
	}
}

func (s *Server) Dispatch(repoID int64, ev webhook.Event) {
	ctx := context.Background()
	repo, err := s.Store.RepoByID(ctx, repoID)
	if err != nil {
		return
	}
	if ev.Project == "" {
		ev.Project = repo.FullPath()
	}
	if !strings.HasPrefix(ev.URL, "http") {
		ev.URL = strings.TrimRight(s.Cfg.BaseURL, "/") + ev.URL
	}
	if repo.OwnerKind == "group" {
		if g, err := s.Store.GroupByID(ctx, repo.OwnerID); err == nil {
			ev.Group = g.Path
		}
	}
	patterns, _ := s.Store.ProtectedPatterns(ctx, repo.ID)
	protected := access.BranchProtected(patterns, ev.Branch)
	s.deliver(ctx, "repo", repo.ID, ev, protected)
	if repo.OwnerKind == "group" {
		s.deliver(ctx, "group", repo.OwnerID, ev, protected)
	}
	if ev.Type == webhook.EventPipelineFailure {
		s.queueFailureMail(repo, ev)
	}
}

func (s *Server) deliver(ctx context.Context, kind string, scopeID int64, ev webhook.Event, refProtected bool) {
	hooks, err := s.Store.ListWebhooks(ctx, kind, scopeID)
	if err != nil {
		return
	}
	secrets, err := s.Store.SecretValues(ctx, kind, scopeID, refProtected)
	if err != nil {
		s.Log.Error("geheimen voor webhook", "err", err)
		return
	}
	client := ssrf.NewClient(10 * time.Second)
	for _, h := range hooks {
		if !h.Active {
			continue
		}
		ok, err := webhook.Allows(webhook.Hook{Preset: h.Preset, Events: h.Events, BranchFilter: h.BranchFilter}, ev)
		if err != nil {
			_ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
			continue
		}
		if !ok {
			continue
		}
		rawURL, err := webhook.Expand(h.URLTemplate, ev, secrets)
		if err != nil {
			_ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
			continue
		}
		target, err := urlParse(rawURL)
		if err != nil {
			_ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
			continue
		}
		if err := ssrf.ValidateURL(target); err != nil {
			_ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
			continue
		}
		headers, err := webhook.RenderHeaders(h.Preset, h.Headers, ev, secrets)
		if err != nil {
			_ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
			continue
		}
		body, err := webhook.RenderBody(h.BodyTemplate, ev, secrets)
		if err != nil {
			_ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
			continue
		}
		method := h.Method
		if method == "" {
			method = http.MethodPost
		}
		req, err := http.NewRequestWithContext(ctx, method, rawURL, bytes.NewReader(body))
		if err != nil {
			_ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
			continue
		}
		for k, v := range headers {
			if strings.ContainsAny(k, "\r\n") || strings.ContainsAny(v, "\r\n") {
				continue
			}
			req.Header.Set(k, v)
		}
		res, err := client.Do(req)
		if err != nil {
			_ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
			continue
		}
		_, _ = io.Copy(io.Discard, io.LimitReader(res.Body, 1<<20))
		res.Body.Close()
		_ = s.Store.AddDelivery(ctx, h.ID, ev.Type, res.StatusCode, "")
	}
}

func urlParse(raw string) (*url.URL, error) {
	u, err := url.Parse(raw)
	if err != nil {
		return nil, i18n.E("err.whURL")
	}
	return u, nil
}

func gitSHA(r *http.Request, gitBin, dir, rev string) (string, error) {
	out, err := exec.CommandContext(r.Context(), gitBin, "-C", dir, "rev-parse", "--verify", rev+"^{commit}").Output()
	if err != nil {
		return "", err
	}
	return strings.TrimSpace(string(out)), nil
}
