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
		}
		branch, ok := gitrepo.BranchOfRef(ref)
		if !ok || isZero(sha) {
			continue
		}
		s.recordPushContributions(repo, user, map[string]string{ref: before[ref]}, map[string]string{ref: sha})
		s.startPipeline(context.Background(), repo, sha, ref, 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 string) {
	if !s.Cfg.CI.Enabled || s.StoragePath() == "" {
		return
	}
	dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
	raw, err := exec.CommandContext(ctx, s.Git, "-C", dir, "show", sha+":blue-ci-cd.yml").Output()
	if err != nil {
		return
	}
	spec, err := ci.Parse(raw)
	branch, _ := gitrepo.BranchOfRef(ref)
	if branch == "" {
		branch = ref
	}
	if err != nil {
		_ = s.Store.RecordConfigFailure(ctx, repo.ID, sha, ref, "blue-ci-cd.yml: "+err.Error())
		return
	}
	env := map[string]string{"CI_COMMIT_BRANCH": branch, "CI_COMMIT_SHA": sha, "CI_COMMIT_REF": ref}
	active, err := spec.ActiveJobs(env)
	if err != nil {
		_ = s.Store.RecordConfigFailure(ctx, repo.ID, sha, ref, err.Error())
		return
	}
	if len(active) == 0 {
		return
	}
	var jobs []store.NewJob
	for i, j := range active {
		vars := map[string]string{}
		for k, v := range spec.Variables {
			vars[k] = v
		}
		for k, v := range j.Variables {
			vars[k] = v
		}
		needs := j.Needs
		if needs == nil {
			needs = []string{}
		}
		paths := j.Artifacts.Paths
		if paths == nil {
			paths = []string{}
		}
		jobs = append(jobs, store.NewJob{
			Name: j.Name, Stage: j.Stage, Position: i, Image: j.Image,
			Script: strings.Join(j.Script, "\n"), Needs: needs, NeedsSet: j.NeedsSet,
			Variables: vars, ArtifactPaths: paths, ArtifactExpire: j.Artifacts.ExpireIn,
			AllowFailure: j.AllowFailure,
		})
	}
	if _, err := s.Store.CreatePipeline(ctx, repo.ID, sha, ref, jobs); err != nil && s.Log != nil {
		s.Log.Error("pipeline", "err", err)
	}
	_ = actor
}

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)
	}
}

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
}
