package server

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

	"gitlab.com/Timfa/bluegit/internal/access"
	"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"`
	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.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.guard(w, r, access.RoleReadonly)
	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)
}

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
}
