package server

import (
	"context"
	"net/http"

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

// SecretChoice is een geheimnaam die een webhook mag noemen.
// De waarde zit er niet bij.
type SecretChoice struct {
	Name   string `json:"name"`
	Source string `json:"source"`
	Label  string `json:"label"`
}

func (s *Server) repoSecretChoices(r *http.Request, repo store.Repo) []SecretChoice {
	var out []SecretChoice
	if repo.OwnerKind == "group" {
		if g, err := s.Store.GroupByID(r.Context(), repo.OwnerID); err == nil {
			out = append(out, s.choicesFrom(r, "group", g.ID, s.tr(r, "wh.src.group", g.Path))...)
		}
	}
	out = append(out, s.choicesFrom(r, "repo", repo.ID, s.tr(r, "wh.src.repo", repo.FullPath()))...)
	if out == nil {
		out = []SecretChoice{}
	}
	return out
}

func (s *Server) groupSecretChoices(r *http.Request, g store.Group) []SecretChoice {
	out := s.choicesFrom(r, "group", g.ID, s.tr(r, "wh.src.group", g.Path))
	if out == nil {
		out = []SecretChoice{}
	}
	return out
}

func (s *Server) choicesFrom(r *http.Request, kind string, id int64, label string) []SecretChoice {
	list, err := s.Store.ListSecrets(r.Context(), kind, id)
	if err != nil || len(list) == 0 {
		return nil
	}
	out := make([]SecretChoice, 0, len(list))
	for _, m := range list {
		out = append(out, SecretChoice{Name: m.Name, Source: kind, Label: label})
	}
	return out
}

// hookSecrets geeft de namen die een webhook mag invullen.
// Een repository-webhook ziet eerst de groepsgeheimen en daarna de
// eigen geheimen; dezelfde naam laat de repository winnen.
func (s *Server) hookSecrets(ctx context.Context, kind string, scopeID int64, refProtected bool, repo store.Repo) (map[string]string, error) {
	out := map[string]string{}
	if kind == "repo" && repo.OwnerKind == "group" {
		groupVals, err := s.Store.SecretValues(ctx, "group", repo.OwnerID, refProtected)
		if err != nil {
			return nil, err
		}
		for k, v := range groupVals {
			out[k] = v
		}
	}
	own, err := s.Store.SecretValues(ctx, kind, scopeID, refProtected)
	if err != nil {
		return nil, err
	}
	for k, v := range own {
		out[k] = v
	}
	return out, nil
}
