package server

import (
	"net/http"
	"strconv"
	"strings"
	"time"

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

func rfcTime(t time.Time) any {
	if t.IsZero() {
		return nil
	}
	return t.UTC().Format(time.RFC3339)
}

func userJSON(u store.User, self bool, web string) map[string]any {
	out := map[string]any{
		"id": u.ID, "username": u.Username, "avatar_url": u.AvatarURL,
		"name": strings.TrimSpace(u.DisplayName), "bio": u.Bio,
		"created_at": rfcTime(u.CreatedAt),
	}
	if web != "" {
		out["web_url"] = web
	}
	if self {
		out["instance_admin"] = u.InstanceAdmin
		out["language"] = u.Language
	}
	return out
}

func tokenJSON(t store.TokenInfo, plain string) map[string]any {
	out := map[string]any{
		"id": t.ID, "name": t.Name, "prefix": t.Prefix,
		"scopes":       access.StoredScopes(t.Scopes).List(),
		"created_at":   rfcTime(t.CreatedAt),
		"last_used_at": rfcTime(t.LastUsedAt),
		"expires_at":   rfcTime(t.ExpiresAt),
	}
	if plain != "" {
		out["token"] = plain
	}
	return out
}

func (s *Server) apiGetUser(w http.ResponseWriter, r *http.Request) {
	u := apiUser(r)
	writeJSON(w, http.StatusOK, userJSON(u, true, s.absURL("/users/"+u.Username)))
}

func (s *Server) apiPutUser(w http.ResponseWriter, r *http.Request) {
	var in struct {
		Language *string `json:"language"`
		Name     *string `json:"name"`
		Bio      *string `json:"bio"`
	}
	if err := readJSON(r, &in); err != nil {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
		return
	}
	u := apiUser(r)
	if in.Language != nil {
		if _, err := s.opSetLanguage(r.Context(), u, *in.Language); !s.apiOK(w, r, err) {
			return
		}
	}
	if in.Name != nil || in.Bio != nil {
		name, bio := u.DisplayName, u.Bio
		if in.Name != nil {
			name = *in.Name
		}
		if in.Bio != nil {
			bio = *in.Bio
		}
		if _, err := s.opSetProfile(r.Context(), u, name, bio); !s.apiOK(w, r, err) {
			return
		}
	}
	fresh, err := s.Store.UserByID(r.Context(), u.ID)
	if !s.apiOK(w, r, err) {
		return
	}
	writeJSON(w, http.StatusOK, userJSON(fresh, true, s.absURL("/users/"+fresh.Username)))
}

func (s *Server) apiExport(w http.ResponseWriter, r *http.Request) {
	writeJSON(w, http.StatusOK, s.opExport(r.Context(), apiUser(r)))
}

func (s *Server) apiUserByName(w http.ResponseWriter, r *http.Request) {
	u, err := s.Store.UserByUsername(r.Context(), r.PathValue("username"))
	if err != nil {
		s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
		return
	}
	viewer := apiUser(r).ID
	ids, err := s.Store.ListRepoIDs(r.Context(), viewer)
	if err != nil {
		ids = nil
	}
	heat := s.heatmap(r.Context(), u.ID, ids, s.langOf(r))
	total := 0
	if heat != nil {
		total = heat.Total
	}
	card, repos, groups := s.profileCard(r, u, viewer, total)
	out := userJSON(u, viewer == u.ID, card.URL)
	out["counts"] = map[string]any{
		"repos": card.Repos, "groups": card.Groups, "contributions": card.Contrib,
	}
	out["repos"] = repoBriefs(s, repos)
	out["groups"] = groupBriefs(s, groups)
	writeJSON(w, http.StatusOK, out)
}

func repoBriefs(s *Server, repos []store.Repo) []map[string]any {
	out := make([]map[string]any, 0, len(repos))
	for _, repo := range repos {
		out = append(out, map[string]any{
			"id": repo.ID, "name": repo.Name, "path": repo.FullPath(),
			"description": repo.Description, "visibility": repo.Visibility,
			"web_url": s.absURL("/" + repo.FullPath()),
		})
	}
	return out
}

func groupBriefs(s *Server, groups []store.Group) []map[string]any {
	out := make([]map[string]any, 0, len(groups))
	for _, g := range groups {
		out = append(out, map[string]any{
			"id": g.ID, "name": g.Name, "path": g.Path,
			"description": g.Description, "visibility": g.Visibility,
			"web_url": s.absURL("/groups/" + g.Path),
		})
	}
	return out
}

func (s *Server) apiListTokens(w http.ResponseWriter, r *http.Request) {
	list, err := s.Store.ListTokens(r.Context(), apiUser(r).ID)
	if !s.apiOK(w, r, err) {
		return
	}
	page, per := pageQuery(r)
	rows := make([]map[string]any, 0, len(list))
	for _, t := range list {
		rows = append(rows, tokenJSON(t, ""))
	}
	writePage(w, r, slicePage(rows, page, per), len(rows), page, per)
}

func (s *Server) apiCreateToken(w http.ResponseWriter, r *http.Request) {
	var in struct {
		Name      string   `json:"name"`
		Scopes    []string `json:"scopes"`
		ExpiresAt string   `json:"expires_at"`
	}
	if err := readJSON(r, &in); err != nil {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
		return
	}
	var exp time.Time
	if in.ExpiresAt != "" {
		parsed, err := time.Parse(time.RFC3339, in.ExpiresAt)
		if err != nil {
			s.writeAPIErr(w, r, fail(400, i18n.E("err.tokenExpired")))
			return
		}
		exp = parsed
	}
	plain, info, err := s.opIssueToken(r.Context(), apiUser(r), in.Name, in.Scopes, exp)
	if !s.apiOK(w, r, err) {
		return
	}
	writeJSON(w, http.StatusCreated, tokenJSON(info, plain))
}

func (s *Server) apiDeleteToken(w http.ResponseWriter, r *http.Request) {
	id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
	if err != nil {
		s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
		return
	}
	if !s.apiOK(w, r, s.opRevokeToken(r.Context(), apiUser(r), id)) {
		return
	}
	writeJSON(w, http.StatusNoContent, nil)
}

func keyJSON(k store.SSHKey) map[string]any {
	return map[string]any{
		"id": k.ID, "name": k.Name, "key": k.PublicKey, "fingerprint": k.Fingerprint,
		"created_at": rfcTime(k.CreatedAt),
	}
}

func (s *Server) apiListKeys(w http.ResponseWriter, r *http.Request) {
	list, err := s.Store.ListSSHKeys(r.Context(), apiUser(r).ID)
	if !s.apiOK(w, r, err) {
		return
	}
	page, per := pageQuery(r)
	rows := make([]map[string]any, 0, len(list))
	for _, k := range list {
		rows = append(rows, keyJSON(k))
	}
	writePage(w, r, slicePage(rows, page, per), len(rows), page, per)
}

func (s *Server) apiAddKey(w http.ResponseWriter, r *http.Request) {
	var in struct {
		Name string `json:"name"`
		Key  string `json:"key"`
	}
	if err := readJSON(r, &in); err != nil {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
		return
	}
	if !s.apiOK(w, r, s.opAddSSH(r.Context(), apiUser(r), in.Name, in.Key)) {
		return
	}
	writeJSON(w, http.StatusCreated, map[string]any{"name": in.Name})
}

func (s *Server) apiDeleteKey(w http.ResponseWriter, r *http.Request) {
	id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
	if err != nil {
		s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
		return
	}
	if !s.apiOK(w, r, s.opRemoveSSH(r.Context(), apiUser(r), id)) {
		return
	}
	writeJSON(w, http.StatusNoContent, nil)
}

func (s *Server) apiAdminStorage(w http.ResponseWriter, r *http.Request) {
	if !apiUser(r).InstanceAdmin {
		s.writeAPIErr(w, r, fail(403, i18n.E("err.forbidden")))
		return
	}
	if r.Method == http.MethodGet {
		writeJSON(w, http.StatusOK, map[string]any{"path": s.StoragePath()})
		return
	}
	var in struct {
		Path string `json:"path"`
	}
	if err := readJSON(r, &in); err != nil {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
		return
	}
	info, moved, err := s.opSetStorage(in.Path)
	if !s.apiOK(w, r, err) {
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{"path": info.Path, "moved": moved, "free": info.Free})
}
