package server

import (
	"io"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"strings"

	"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/store"
)

type releaseRequest struct {
	Tag    string `json:"tag"`
	Commit string `json:"commit"`
	Name   string `json:"name"`
	Body   string `json:"body"`
	// Replace: een job mag zijn eigen release vervangen (zie checkReplace).
	Replace bool `json:"replace"`
	Assets  []struct {
		Job  string `json:"job"`
		Path string `json:"path"`
		Name string `json:"name"`
	} `json:"assets"`
}

func (s *Server) createRelease(w http.ResponseWriter, r *http.Request) {
	repo, err := s.Store.RepoByPath(r.Context(), r.PathValue("owner"), r.PathValue("repo"))
	if err != nil {
		s.writeAPIErr(w, r, fail(http.StatusNotFound, i18n.E("err.notFound")))
		return
	}
	token := tokenFrom(r)
	var job store.Job
	var author store.User
	if strings.HasPrefix(token, "bgj_") {
		job, err = s.Store.JobByToken(r.Context(), token)
		if err != nil || job.RepoID != repo.ID || job.Status != "running" {
			s.writeAPIErr(w, r, fail(http.StatusUnauthorized, i18n.E("err.jobToken")))
			return
		}
	} else {
		author = apiUser(r)
		if author.ID == 0 {
			s.writeAPIErr(w, r, fail(http.StatusUnauthorized, i18n.E("err.apiAuth")))
			return
		}
		role, err := s.Store.EffectiveRole(r.Context(), author.ID, repo.ID)
		if err == nil && !role.CanRead() && repo.Visibility != "public" {
			s.writeAPIErr(w, r, fail(http.StatusNotFound, i18n.E("err.notFound")))
			return
		}
		if err != nil || !role.AtLeast(access.RoleMaintainer) {
			s.writeAPIErr(w, r, fail(http.StatusForbidden, i18n.E("err.onlyAdmin")))
			return
		}
	}
	var req releaseRequest
	if err := readJSON(r, &req); err != nil {
		s.writeAPIErr(w, r, fail(http.StatusBadRequest, i18n.E("err.json")))
		return
	}
	id, err := s.opPublishRelease(r.Context(), repo, author, job, req)
	if !s.apiOK(w, r, err) {
		return
	}
	writeJSON(w, http.StatusCreated, map[string]any{"id": id, "tag": req.Tag, "commit": req.Commit})
}

func (s *Server) releaseAsset(w http.ResponseWriter, r *http.Request) {
	_, repo, _, ok := s.guardReleases(w, r)
	if !ok {
		return
	}
	rel, err := s.Store.ReleaseByTag(r.Context(), repo.ID, r.PathValue("tag"))
	if err != nil {
		http.NotFound(w, r)
		return
	}
	name := r.PathValue("name")
	for _, a := range rel.Assets {
		if a.Name == name {
			w.Header().Set("Content-Disposition", "attachment; filename=\""+strings.ReplaceAll(name, "\"", "")+"\"")
			http.ServeFile(w, r, a.StoragePath)
			return
		}
	}
	http.NotFound(w, r)
}

// jobLogAPI geeft de volledige console-output van een job, met geheimen gemaskeerd.
// Een persoonlijk token is verplicht, ook bij een publieke repo. Job-tokens tellen niet.
func (s *Server) jobLogAPI(w http.ResponseWriter, r *http.Request) {
	repo, err := s.Store.RepoByPath(r.Context(), r.PathValue("owner"), r.PathValue("repo"))
	if err != nil {
		http.NotFound(w, r)
		return
	}
	if !s.authorizeRepoRead(w, r, repo) {
		return
	}
	id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
	if err != nil || id <= 0 {
		http.NotFound(w, r)
		return
	}
	job, err := s.Store.JobByID(r.Context(), repo.ID, id)
	if err != nil {
		http.NotFound(w, r)
		return
	}
	text := ci.Mask(job.Log, s.maskSecrets(r.Context(), repo))
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	w.Header().Set("Cache-Control", "no-store")
	_, _ = w.Write([]byte(text))
}

// authorizeRepoRead eist een persoonlijk token. Op een publieke repo volstaat
// elk geldig token. Op een privérepo moet het token de repo mogen lezen.
func (s *Server) authorizeRepoRead(w http.ResponseWriter, r *http.Request, repo store.Repo) bool {
	token := bearer(r)
	if token == "" {
		http.Error(w, s.tr(r, "err.tokenAbsent"), http.StatusUnauthorized)
		return false
	}
	if strings.HasPrefix(token, "bgj_") {
		job, err := s.Store.JobByToken(r.Context(), token)
		if err == nil && job.Status == "running" && job.RepoID == repo.ID {
			return true
		}
		http.Error(w, s.tr(r, "err.tokenBad"), http.StatusUnauthorized)
		return false
	}
	if !strings.HasPrefix(token, "bg_") {
		http.Error(w, s.tr(r, "err.tokenBad"), http.StatusUnauthorized)
		return false
	}
	u, err := s.Store.UserByToken(r.Context(), token)
	if err != nil {
		http.Error(w, s.tr(r, "err.tokenBad"), http.StatusUnauthorized)
		return false
	}
	role, err := s.Store.EffectiveRole(r.Context(), u.ID, repo.ID)
	if err != nil {
		http.Error(w, s.tr(r, "err.rights"), http.StatusInternalServerError)
		return false
	}
	if !role.CanRead() && repo.Visibility != "public" {
		http.Error(w, s.tr(r, "err.forbidden"), http.StatusForbidden)
		return false
	}
	return true
}

// commitDiffAPI geeft de unified diff van één commit.
func (s *Server) commitDiffAPI(w http.ResponseWriter, r *http.Request) {
	repo, err := s.Store.RepoByPath(r.Context(), r.PathValue("owner"), r.PathValue("repo"))
	if err != nil {
		http.NotFound(w, r)
		return
	}
	if !s.authorizeRepoRead(w, r, repo) {
		return
	}
	sha := r.PathValue("sha")
	if !safeSHA(sha) || s.Git == "" || s.StoragePath() == "" {
		http.NotFound(w, r)
		return
	}
	text, err := gitrepo.CommitDiff(r.Context(), s.Git, gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name), sha)
	if err != nil {
		http.NotFound(w, r)
		return
	}
	writePlain(w, text)
}

// mrDiffAPI geeft de three-dot diff van een merge request.
func (s *Server) mrDiffAPI(w http.ResponseWriter, r *http.Request) {
	repo, err := s.Store.RepoByPath(r.Context(), r.PathValue("owner"), r.PathValue("repo"))
	if err != nil {
		http.NotFound(w, r)
		return
	}
	if !s.authorizeRepoRead(w, r, repo) {
		return
	}
	number, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
	if err != nil || number <= 0 || s.Git == "" || s.StoragePath() == "" {
		http.NotFound(w, r)
		return
	}
	mr, err := s.Store.MergeRequestByNumber(r.Context(), repo.ID, number)
	if err != nil || safeRev(mr.SourceBranch, "") != mr.SourceBranch || safeRev(mr.TargetBranch, "") != mr.TargetBranch {
		http.NotFound(w, r)
		return
	}
	text, err := gitrepo.CompareDiff(r.Context(), s.Git, gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name), mr.TargetBranch, mr.SourceBranch)
	if err != nil {
		http.NotFound(w, r)
		return
	}
	writePlain(w, text)
}

func writePlain(w http.ResponseWriter, text string) {
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	w.Header().Set("Cache-Control", "no-store")
	_, _ = w.Write([]byte(text))
}

func bearer(r *http.Request) string {
	h := r.Header.Get("Authorization")
	if strings.HasPrefix(strings.ToLower(h), "bearer ") {
		return strings.TrimSpace(h[7:])
	}
	return ""
}

func copyRelease(src, dst string) error {
	if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
		return err
	}
	in, err := os.Open(src)
	if err != nil {
		return err
	}
	defer in.Close()
	out, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o644)
	if err != nil {
		return err
	}
	defer out.Close()
	_, err = io.Copy(out, in)
	return err
}
