package server

import (
	"context"
	"strings"
	"time"

	"gitlab.com/Timfa/bluegit/internal/access"
	"gitlab.com/Timfa/bluegit/internal/i18n"
	"gitlab.com/Timfa/bluegit/internal/store"
	"golang.org/x/crypto/ssh"
)

func (s *Server) opIssueToken(ctx context.Context, user store.User, name string, scopes []string, expires time.Time) (string, store.TokenInfo, error) {
	stored, _, err := access.ParseScopes(scopes)
	if err != nil {
		return "", store.TokenInfo{}, fail(400, err)
	}
	plain, info, err := s.Store.IssueToken(ctx, user.ID, store.TokenRequest{Name: name, Scopes: stored, ExpiresAt: expires})
	if err != nil {
		return "", store.TokenInfo{}, fail(400, err)
	}
	return plain, info, nil
}

func (s *Server) opRevokeToken(ctx context.Context, user store.User, id int64) error {
	if err := s.Store.DeleteToken(ctx, user.ID, id); err != nil {
		return notFound(err)
	}
	return nil
}

func (s *Server) opAddSSH(ctx context.Context, user store.User, name, line string) error {
	line = strings.TrimSpace(line)
	pub, _, _, _, err := ssh.ParseAuthorizedKey([]byte(line))
	if err != nil {
		return fail(400, i18n.E("err.sshBad"))
	}
	stored := strings.TrimSpace(string(ssh.MarshalAuthorizedKey(pub)))
	if err := s.Store.AddSSHKey(ctx, user.ID, name, stored, ssh.FingerprintSHA256(pub)); err != nil {
		return fail(400, err)
	}
	return nil
}

func (s *Server) opRemoveSSH(ctx context.Context, user store.User, id int64) error {
	if err := s.Store.DeleteSSHKey(ctx, user.ID, id); err != nil {
		return notFound(err)
	}
	return nil
}

func (s *Server) opSetLanguage(ctx context.Context, user store.User, raw string) (i18n.Lang, error) {
	lang := i18n.Parse(raw)
	if err := s.Store.SetLanguage(ctx, user.ID, string(lang)); err != nil {
		return lang, fail(400, err)
	}
	return lang, nil
}

func (s *Server) opExport(ctx context.Context, u store.User) map[string]any {
	type secretRow struct {
		Scope string `json:"scope"`
		Name  string `json:"name"`
		Value string `json:"value"`
	}
	var secrets []secretRow
	ids, _ := s.Store.ListRepoIDs(ctx, u.ID)
	for _, id := range ids {
		role, err := s.Store.EffectiveRole(ctx, u.ID, id)
		if err != nil || !role.CanManageSecrets() {
			continue
		}
		repo, err := s.Store.RepoByID(ctx, id)
		if err != nil {
			continue
		}
		vals, err := s.Store.SecretValues(ctx, "repo", id, true)
		if err != nil {
			continue
		}
		for name, value := range vals {
			secrets = append(secrets, secretRow{Scope: "repo:" + repo.FullPath(), Name: name, Value: value})
		}
	}
	groups, _ := s.Store.ListGroups(ctx, u.ID)
	for _, g := range groups {
		role, err := s.Store.GroupRole(ctx, g.ID, u.ID)
		if err != nil || !role.AtLeast(access.RoleMaintainer) {
			continue
		}
		vals, err := s.Store.SecretValues(ctx, "group", g.ID, true)
		if err != nil {
			continue
		}
		for name, value := range vals {
			secrets = append(secrets, secretRow{Scope: "group:" + g.Path, Name: name, Value: value})
		}
	}
	tokens, _ := s.Store.ListTokens(ctx, u.ID)
	keys, _ := s.Store.ListSSHKeys(ctx, u.ID)
	return map[string]any{
		"exported_at": time.Now().UTC().Format(time.RFC3339),
		"account": map[string]any{
			"id": u.AuthID, "username": u.Username, "avatar_url": u.AvatarURL, "instance_admin": u.InstanceAdmin,
		},
		"tokens": tokens, "ssh_keys": keys, "secrets": secrets,
	}
}
