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])
			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])
		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) {
	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
	}
	read := func(path string) ([]byte, error) {
		if path == "" || strings.Contains(path, "..") || strings.HasPrefix(path, "/") {
			return nil, i18n.E("ci.err.rel", path)
		}
		return exec.CommandContext(ctx, s.Git, "-C", dir, "show", sha+":"+path).Output()
	}
	spec, err := ci.ParseIn(raw, read)
	if err != nil {
		_ = s.Store.RecordConfigFailure(ctx, repo.ID, sha, ref, err.Error())
		return
	}
	name, kind := ci.SplitRef(ref)
	title := strings.TrimSpace(gitOne(ctx, s.Git, dir, "log", "-1", "--format=%s", sha))
	files := gitLines(ctx, s.Git, dir, "ls-tree", "-r", "--name-only", sha)
	changed := changedFiles(ctx, s.Git, dir, sha, before, files)
	env := ci.Variables(ci.Ref{
		SHA: sha, FullRef: ref, Name: name, Kind: kind, Title: title,
		DefaultBranch: repo.DefaultBranch, Source: source, ProjectPath: repo.FullPath(),
	})
	active, err := spec.Select(ci.Eval{Env: env, Changed: changed, Files: files})
	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,
			Before: strings.Join(j.Before, "\n"), Script: strings.Join(j.Script, "\n"), After: strings.Join(j.After, "\n"),
			Needs: needs, Optional: j.Optional, NeedsSet: j.NeedsSet,
			Variables: vars, ArtifactPaths: paths, ArtifactExpire: j.Artifacts.ExpireIn,
			AllowFailure: j.AllowFailure, When: j.When, Timeout: j.Timeout, Tags: j.Tags,
			CachePaths: j.Cache.Paths, CacheKey: j.Cache.Key, ResourceGroup: j.ResourceGroup,
		})
	}
	if _, err := s.Store.CreatePipeline(ctx, repo.ID, sha, ref, source, actor, title, jobs); err != nil && s.Log != nil {
		s.Log.Error("pipeline", "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
}
