package server

import (
	"encoding/json"
	"io"
	"net/http"
	"strings"
	"time"

	"gitlab.com/Timfa/bluegit/internal/store"
)

type secretBody struct {
	Name      string `json:"name"`
	Value     string `json:"value"`
	Protected bool   `json:"protected"`
	Invisible bool   `json:"invisible"`
	Expand    *bool  `json:"expand"`
}

func (s *Server) repoSecretsAPI(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.secretAPIRepo(w, r)
	if !ok {
		return
	}
	s.secretListAPI(w, r, "repo", repo.ID)
}

func (s *Server) groupSecretsAPI(w http.ResponseWriter, r *http.Request) {
	g, _, ok := s.secretAPIGroup(w, r)
	if !ok {
		return
	}
	s.secretListAPI(w, r, "group", g.ID)
}

func (s *Server) repoSecretCreateAPI(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.secretAPIRepo(w, r)
	if !ok {
		return
	}
	s.secretWriteAPI(w, r, "repo", repo.ID, "create")
}

func (s *Server) groupSecretCreateAPI(w http.ResponseWriter, r *http.Request) {
	g, _, ok := s.secretAPIGroup(w, r)
	if !ok {
		return
	}
	s.secretWriteAPI(w, r, "group", g.ID, "create")
}

func (s *Server) repoSecretRevealAPI(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.secretAPIRepo(w, r)
	if !ok {
		return
	}
	s.secretRevealAPI(w, r, "repo", repo.ID)
}

func (s *Server) groupSecretRevealAPI(w http.ResponseWriter, r *http.Request) {
	g, _, ok := s.secretAPIGroup(w, r)
	if !ok {
		return
	}
	s.secretRevealAPI(w, r, "group", g.ID)
}

func (s *Server) repoSecretUpdateAPI(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.secretAPIRepo(w, r)
	if !ok {
		return
	}
	s.secretWriteAPI(w, r, "repo", repo.ID, "update")
}

func (s *Server) groupSecretUpdateAPI(w http.ResponseWriter, r *http.Request) {
	g, _, ok := s.secretAPIGroup(w, r)
	if !ok {
		return
	}
	s.secretWriteAPI(w, r, "group", g.ID, "update")
}

func (s *Server) repoSecretReplaceAPI(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.secretAPIRepo(w, r)
	if !ok {
		return
	}
	s.secretWriteAPI(w, r, "repo", repo.ID, "replace")
}

func (s *Server) groupSecretReplaceAPI(w http.ResponseWriter, r *http.Request) {
	g, _, ok := s.secretAPIGroup(w, r)
	if !ok {
		return
	}
	s.secretWriteAPI(w, r, "group", g.ID, "replace")
}

func (s *Server) repoSecretDeleteAPI(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.secretAPIRepo(w, r)
	if !ok {
		return
	}
	s.secretDeleteAPI(w, r, "repo", repo.ID)
}

func (s *Server) groupSecretDeleteAPI(w http.ResponseWriter, r *http.Request) {
	g, _, ok := s.secretAPIGroup(w, r)
	if !ok {
		return
	}
	s.secretDeleteAPI(w, r, "group", g.ID)
}

func (s *Server) secretAPIRepo(w http.ResponseWriter, r *http.Request) (store.Repo, store.User, bool) {
	u, ok := s.webhookAPIUser(w, r)
	if !ok {
		return store.Repo{}, store.User{}, false
	}
	repo, err := s.Store.RepoByPath(r.Context(), r.PathValue("owner"), r.PathValue("repo"))
	if err != nil {
		http.NotFound(w, r)
		return store.Repo{}, store.User{}, false
	}
	role, err := s.Store.EffectiveRole(r.Context(), u.ID, repo.ID)
	if err != nil || !role.CanManageSecrets() {
		http.Error(w, s.tr(r, "err.onlyAdmin"), http.StatusForbidden)
		return store.Repo{}, store.User{}, false
	}
	return repo, u, true
}

func (s *Server) secretAPIGroup(w http.ResponseWriter, r *http.Request) (store.Group, store.User, bool) {
	u, ok := s.webhookAPIUser(w, r)
	if !ok {
		return store.Group{}, store.User{}, false
	}
	g, err := s.Store.GroupByPath(r.Context(), r.PathValue("path"))
	if err != nil {
		http.NotFound(w, r)
		return store.Group{}, store.User{}, false
	}
	role, err := s.Store.GroupRole(r.Context(), g.ID, u.ID)
	if err != nil || !role.CanManageSecrets() {
		http.Error(w, s.tr(r, "err.onlyAdmin"), http.StatusForbidden)
		return store.Group{}, store.User{}, false
	}
	return g, u, true
}

func (s *Server) secretListAPI(w http.ResponseWriter, r *http.Request, kind string, scopeID int64) {
	list, err := s.Store.ListSecrets(r.Context(), kind, scopeID)
	if err != nil {
		http.Error(w, s.trErr(r, err), http.StatusInternalServerError)
		return
	}
	out := make([]map[string]any, 0, len(list))
	for _, m := range list {
		out = append(out, secretMetaJSON(m))
	}
	resp := map[string]any{"secrets": out}
	if kind == "repo" {
		if repo, err := s.Store.RepoByID(r.Context(), scopeID); err == nil {
			resp["inherited"] = inheritedJSON(s.inheritedSecrets(r.Context(), repo))
		}
	}
	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(resp)
}

func (s *Server) secretWriteAPI(w http.ResponseWriter, r *http.Request, kind string, scopeID int64, mode string) {
	var body secretBody
	if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&body); err != nil {
		http.Error(w, s.tr(r, "err.json"), http.StatusBadRequest)
		return
	}
	name := strings.TrimSpace(body.Name)
	if mode != "create" {
		name = strings.TrimSpace(r.PathValue("name"))
	}
	var err error
	switch mode {
	case "update":
		err = s.Store.UpdateSecret(r.Context(), kind, scopeID, name, body.Value, body.Protected)
	case "replace":
		err = s.Store.ReplaceSecret(r.Context(), kind, scopeID, name, body.Value, body.Protected)
	default:
		err = s.Store.CreateSecret(r.Context(), kind, scopeID, name, body.Value, body.Protected, body.Invisible)
	}
	if err != nil {
		s.writeSecretErr(w, r, err)
		return
	}
	if body.Expand != nil {
		_ = s.Store.SetSecretExpand(r.Context(), kind, scopeID, name, *body.Expand)
	}
	meta, err := s.secretMeta(r, kind, scopeID, name)
	if err != nil {
		s.writeSecretErr(w, r, err)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	if mode == "create" {
		w.WriteHeader(http.StatusCreated)
	}
	_ = json.NewEncoder(w).Encode(secretMetaJSON(meta))
}

func (s *Server) secretRevealAPI(w http.ResponseWriter, r *http.Request, kind string, scopeID int64) {
	name := strings.TrimSpace(r.PathValue("name"))
	value, err := s.Store.RevealSecret(r.Context(), kind, scopeID, name)
	if err != nil {
		s.writeSecretErr(w, r, err)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(map[string]string{"name": name, "value": value})
}

func (s *Server) secretDeleteAPI(w http.ResponseWriter, r *http.Request, kind string, scopeID int64) {
	if err := s.Store.DeleteSecret(r.Context(), kind, scopeID, strings.TrimSpace(r.PathValue("name"))); err != nil {
		s.writeSecretErr(w, r, err)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

func (s *Server) secretMeta(r *http.Request, kind string, scopeID int64, name string) (store.SecretMeta, error) {
	list, err := s.Store.ListSecrets(r.Context(), kind, scopeID)
	if err != nil {
		return store.SecretMeta{}, err
	}
	for _, m := range list {
		if m.Name == name {
			return m, nil
		}
	}
	return store.SecretMeta{}, store.NotFound()
}

func secretMetaJSON(m store.SecretMeta) map[string]any {
	created := ""
	if !m.CreatedAt.IsZero() {
		created = m.CreatedAt.UTC().Format(time.RFC3339)
	}
	return map[string]any{
		"name":       m.Name,
		"protected":  m.Protected,
		"invisible":  m.Invisible,
		"expand":     m.Expand,
		"created_at": created,
	}
}

func (s *Server) writeSecretErr(w http.ResponseWriter, r *http.Request, err error) {
	http.Error(w, s.trErr(r, err), secretStatus(err))
}
