package server

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

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

type issueWrite struct {
	Title        *string   `json:"title"`
	Description  *string   `json:"description"`
	State        *string   `json:"state"`
	Confidential *bool     `json:"confidential"`
	Labels       *[]string `json:"labels"`
	Assignees    *[]string `json:"assignees"`
	Milestone    *string   `json:"milestone"`
	DueDate      *string   `json:"due_date"`
}

func (s *Server) issuesAPI(w http.ResponseWriter, r *http.Request) {
	write := r.Method == http.MethodPost
	u, repo, role, ok := s.issueAuth(w, r, write)
	if !ok {
		return
	}
	if r.Method == http.MethodGet {
		state := r.URL.Query().Get("state")
		if state != "closed" && state != "all" {
			state = "open"
		}
		list, err := s.Store.ListIssues(r.Context(), repo.ID, store.IssueFilter{
			State: state, Query: r.URL.Query().Get("q"), Label: r.URL.Query().Get("label"),
			Assignee: r.URL.Query().Get("assignee"), ViewerID: u.ID, Triage: role.CanTriageIssue(),
		})
		if err != nil {
			s.fail(w, r, err)
			return
		}
		out := make([]any, 0, len(list))
		for _, iss := range list {
			out = append(out, s.issueJSON(repo, iss, nil))
		}
		writeJSON(w, http.StatusOK, map[string]any{"issues": out})
		return
	}
	if !role.CanCreateIssue() {
		http.Error(w, s.tr(r, "err.forbidden"), http.StatusForbidden)
		return
	}
	var req issueWrite
	if !s.readJSON(w, r, &req) {
		return
	}
	if req.Title == nil || strings.TrimSpace(*req.Title) == "" {
		http.Error(w, s.tr(r, "err.issueTitle"), http.StatusBadRequest)
		return
	}
	in := store.NewIssue{Title: *req.Title}
	if req.Description != nil {
		in.Description = *req.Description
	}
	if req.Confidential != nil {
		in.Confidential = *req.Confidential
	}
	if req.Labels != nil || req.Assignees != nil || req.Milestone != nil || req.DueDate != nil {
		if !role.CanTriageIssue() {
			http.Error(w, s.tr(r, "err.forbidden"), http.StatusForbidden)
			return
		}
		if err := s.applyIssueWrite(r, repo, &in, req); err != nil {
			http.Error(w, s.trErr(r, err), http.StatusBadRequest)
			return
		}
	}
	base := quickBase{Confidential: in.Confidential, Due: in.DueOn}
	if req.Labels != nil {
		base.Labels = *req.Labels
	}
	if req.Assignees != nil {
		base.Assignees = *req.Assignees
	}
	if req.Milestone != nil {
		base.Milestone = *req.Milestone
	}
	q, err := s.foldQuick(r.Context(), repo, in.Description, role.CanTriageIssue(), true, base)
	if err != nil {
		http.Error(w, s.trErr(r, err), http.StatusBadRequest)
		return
	}
	in.Description = q.Body
	if q.Labels {
		in.LabelIDs = q.LabelIDs
	}
	if q.Assignees {
		in.AssigneeIDs = q.AssigneeIDs
	}
	if q.Meta {
		in.MilestoneID = q.MilestoneID
		in.DueOn = q.Due
		in.Confidential = q.Confidential
	}
	iss, err := s.Store.CreateIssue(r.Context(), repo.ID, u.ID, in)
	if err != nil {
		http.Error(w, s.trErr(r, err), http.StatusBadRequest)
		return
	}
	s.issueHook(repo, iss.Number, u.Username, "opened", "")
	notes, _ := s.Store.ListIssueNotes(r.Context(), iss.ID)
	writeJSON(w, http.StatusCreated, s.issueJSON(repo, iss, notes))
}

func (s *Server) issueAPI(w http.ResponseWriter, r *http.Request) {
	write := r.Method != http.MethodGet
	u, repo, role, ok := s.issueAuth(w, r, write)
	if !ok {
		return
	}
	n, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
	if err != nil || n < 1 {
		http.NotFound(w, r)
		return
	}
	iss, err := s.Store.IssueByNumber(r.Context(), repo.ID, n)
	if err != nil || !issueVisible(iss, u, role) {
		http.NotFound(w, r)
		return
	}
	if r.Method == http.MethodGet {
		notes, err := s.Store.ListIssueNotes(r.Context(), iss.ID)
		if err != nil {
			s.fail(w, r, err)
			return
		}
		writeJSON(w, http.StatusOK, s.issueJSON(repo, iss, notes))
		return
	}
	if r.Method == http.MethodDelete {
		if !role.CanManageSettings() {
			http.Error(w, s.tr(r, "err.forbidden"), http.StatusForbidden)
			return
		}
		if err := s.Store.DeleteIssue(r.Context(), repo.ID, iss.ID); err != nil {
			http.Error(w, s.trErr(r, err), http.StatusBadRequest)
			return
		}
		w.WriteHeader(http.StatusNoContent)
		return
	}
	if u.ID != iss.AuthorID && !role.CanTriageIssue() {
		http.Error(w, s.tr(r, "err.forbidden"), http.StatusForbidden)
		return
	}
	var req issueWrite
	if !s.readJSON(w, r, &req) {
		return
	}
	if (req.Labels != nil || req.Assignees != nil || req.Milestone != nil || req.DueDate != nil || req.Confidential != nil) && !role.CanTriageIssue() {
		http.Error(w, s.tr(r, "err.forbidden"), http.StatusForbidden)
		return
	}
	action := ""
	var folded quickResult
	base := quickFromIssue(iss)
	if req.Labels != nil {
		base.Labels = *req.Labels
	}
	if req.Assignees != nil {
		base.Assignees = *req.Assignees
	}
	if req.Milestone != nil {
		base.Milestone = *req.Milestone
	}
	if req.DueDate != nil {
		base.Due = *req.DueDate
	}
	if req.Confidential != nil {
		base.Confidential = *req.Confidential
	}
	if req.Title != nil || req.Description != nil {
		title, desc := iss.Title, iss.Description
		if req.Title != nil {
			title = *req.Title
		}
		if req.Description != nil {
			var err error
			folded, err = s.foldQuick(r.Context(), repo, *req.Description, role.CanTriageIssue(), false, base)
			if err != nil {
				http.Error(w, s.trErr(r, err), http.StatusBadRequest)
				return
			}
			desc = folded.Body
		}
		if err := s.Store.UpdateIssueText(r.Context(), iss.ID, title, desc); err != nil {
			http.Error(w, s.trErr(r, err), http.StatusBadRequest)
			return
		}
		if err := s.persistQuick(r.Context(), repo, iss.ID, folded); err != nil {
			http.Error(w, s.trErr(r, err), http.StatusBadRequest)
			return
		}
		action = "updated"
	}
	if req.Labels != nil || req.Assignees != nil || req.Milestone != nil || req.DueDate != nil || req.Confidential != nil {
		if req.Labels != nil && !folded.Labels {
			ids, err := s.resolveLabels(r.Context(), repo.ID, *req.Labels)
			if err != nil {
				http.Error(w, s.trErr(r, err), http.StatusBadRequest)
				return
			}
			if err := s.Store.SetIssueLabels(r.Context(), repo.ID, iss.ID, ids); err != nil {
				http.Error(w, s.trErr(r, err), http.StatusBadRequest)
				return
			}
		}
		if req.Assignees != nil && !folded.Assignees {
			ids, err := s.resolveAssignees(r.Context(), repo, *req.Assignees)
			if err != nil {
				http.Error(w, s.trErr(r, err), http.StatusBadRequest)
				return
			}
			if err := s.Store.SetIssueAssignees(r.Context(), repo.ID, iss.ID, ids); err != nil {
				http.Error(w, s.trErr(r, err), http.StatusBadRequest)
				return
			}
		}
		if !folded.Meta && (req.Milestone != nil || req.DueDate != nil || req.Confidential != nil) {
			mile, due, conf := iss.MilestoneID, iss.DueOn, iss.Confidential
			if req.Milestone != nil {
				id, err := s.resolveMilestone(r.Context(), repo.ID, *req.Milestone)
				if err != nil {
					http.Error(w, s.trErr(r, err), http.StatusBadRequest)
					return
				}
				mile = id
			}
			if req.DueDate != nil {
				due = *req.DueDate
			}
			if req.Confidential != nil {
				conf = *req.Confidential
			}
			if err := s.Store.SetIssueMeta(r.Context(), repo.ID, iss.ID, mile, conf, due); err != nil {
				http.Error(w, s.trErr(r, err), http.StatusBadRequest)
				return
			}
		}
		if action == "" {
			action = "updated"
		}
	}
	if req.State != nil {
		if *req.State != "open" && *req.State != "closed" {
			http.Error(w, s.tr(r, "err.issueState"), http.StatusBadRequest)
			return
		}
		changed, err := s.Store.SetIssueState(r.Context(), iss.ID, *req.State)
		if err != nil {
			http.Error(w, s.trErr(r, err), http.StatusBadRequest)
			return
		}
		if changed {
			if *req.State == "closed" {
				action = "closed"
			} else {
				action = "reopened"
			}
		}
	}
	fresh, err := s.Store.IssueByNumber(r.Context(), repo.ID, n)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	if action != "" {
		comment := ""
		s.issueHook(repo, fresh.Number, u.Username, action, comment)
	}
	notes, _ := s.Store.ListIssueNotes(r.Context(), fresh.ID)
	writeJSON(w, http.StatusOK, s.issueJSON(repo, fresh, notes))
}

func (s *Server) issueNoteAPI(w http.ResponseWriter, r *http.Request) {
	u, repo, role, ok := s.issueAuth(w, r, true)
	if !ok {
		return
	}
	if !role.CanCreateIssue() {
		http.Error(w, s.tr(r, "err.forbidden"), http.StatusForbidden)
		return
	}
	n, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
	if err != nil || n < 1 {
		http.NotFound(w, r)
		return
	}
	iss, err := s.Store.IssueByNumber(r.Context(), repo.ID, n)
	if err != nil || !issueVisible(iss, u, role) {
		http.NotFound(w, r)
		return
	}
	var req struct {
		Body string `json:"body"`
	}
	if !s.readJSON(w, r, &req) {
		return
	}
	q, err := s.foldQuick(r.Context(), repo, req.Body, role.CanTriageIssue(), false, quickFromIssue(iss))
	if err != nil {
		http.Error(w, s.trErr(r, err), http.StatusBadRequest)
		return
	}
	if err := s.persistQuick(r.Context(), repo, iss.ID, q); err != nil {
		http.Error(w, s.trErr(r, err), http.StatusBadRequest)
		return
	}
	if strings.TrimSpace(q.Body) == "" {
		if !q.touched() {
			http.Error(w, s.tr(r, "err.issueNote"), http.StatusBadRequest)
			return
		}
		s.issueHook(repo, iss.Number, u.Username, "updated", "")
		fresh, err := s.Store.IssueByNumber(r.Context(), repo.ID, n)
		if err != nil {
			s.fail(w, r, err)
			return
		}
		notes, _ := s.Store.ListIssueNotes(r.Context(), fresh.ID)
		writeJSON(w, http.StatusOK, s.issueJSON(repo, fresh, notes))
		return
	}
	note, err := s.Store.AddIssueNote(r.Context(), repo.ID, iss.ID, u.ID, q.Body)
	if err != nil {
		http.Error(w, s.trErr(r, err), http.StatusBadRequest)
		return
	}
	s.issueHook(repo, iss.Number, u.Username, "commented", note.Body)
	writeJSON(w, http.StatusCreated, map[string]any{
		"id": note.ID, "author": note.Author, "body": note.Body,
		"created_at": note.CreatedAt.UTC().Format(time.RFC3339),
	})
}

func (s *Server) labelsAPI(w http.ResponseWriter, r *http.Request) {
	u, repo, role, ok := s.issueAuth(w, r, r.Method == http.MethodPost)
	if !ok {
		return
	}
	if r.Method == http.MethodGet {
		list, err := s.Store.ListLabels(r.Context(), repo.ID)
		if err != nil {
			s.fail(w, r, err)
			return
		}
		out := make([]any, 0, len(list))
		for _, l := range list {
			out = append(out, map[string]any{"id": l.ID, "name": l.Name, "color": l.Color})
		}
		writeJSON(w, http.StatusOK, map[string]any{"labels": out})
		return
	}
	if u.ID == 0 || !role.CanManageSettings() {
		http.Error(w, s.tr(r, "err.onlyAdmin"), http.StatusForbidden)
		return
	}
	var req struct {
		Name  string `json:"name"`
		Color string `json:"color"`
	}
	if !s.readJSON(w, r, &req) {
		return
	}
	lab, err := s.Store.UpsertLabel(r.Context(), repo.ID, req.Name, req.Color)
	if err != nil {
		http.Error(w, s.trErr(r, err), http.StatusBadRequest)
		return
	}
	writeJSON(w, http.StatusCreated, map[string]any{"id": lab.ID, "name": lab.Name, "color": lab.Color})
}

func (s *Server) milestonesAPI(w http.ResponseWriter, r *http.Request) {
	u, repo, role, ok := s.issueAuth(w, r, r.Method == http.MethodPost)
	if !ok {
		return
	}
	if r.Method == http.MethodGet {
		list, err := s.Store.ListMilestones(r.Context(), repo.ID)
		if err != nil {
			s.fail(w, r, err)
			return
		}
		out := make([]any, 0, len(list))
		for _, m := range list {
			out = append(out, map[string]any{"id": m.ID, "title": m.Title, "due_on": m.DueOn, "state": m.State})
		}
		writeJSON(w, http.StatusOK, map[string]any{"milestones": out})
		return
	}
	if u.ID == 0 || !role.CanManageSettings() {
		http.Error(w, s.tr(r, "err.onlyAdmin"), http.StatusForbidden)
		return
	}
	var req struct {
		Title string `json:"title"`
		DueOn string `json:"due_on"`
	}
	if !s.readJSON(w, r, &req) {
		return
	}
	m, err := s.Store.UpsertMilestone(r.Context(), repo.ID, req.Title, req.DueOn)
	if err != nil {
		http.Error(w, s.trErr(r, err), http.StatusBadRequest)
		return
	}
	writeJSON(w, http.StatusCreated, map[string]any{"id": m.ID, "title": m.Title, "due_on": m.DueOn, "state": m.State})
}

func (s *Server) applyIssueWrite(r *http.Request, repo store.Repo, in *store.NewIssue, req issueWrite) error {
	if req.Labels != nil {
		ids, err := s.resolveLabels(r.Context(), repo.ID, *req.Labels)
		if err != nil {
			return err
		}
		in.LabelIDs = ids
	}
	if req.Assignees != nil {
		ids, err := s.resolveAssignees(r.Context(), repo, *req.Assignees)
		if err != nil {
			return err
		}
		in.AssigneeIDs = ids
	}
	if req.Milestone != nil {
		id, err := s.resolveMilestone(r.Context(), repo.ID, *req.Milestone)
		if err != nil {
			return err
		}
		in.MilestoneID = id
	}
	if req.DueDate != nil {
		in.DueOn = *req.DueDate
	}
	return nil
}

func (s *Server) issueAuth(w http.ResponseWriter, r *http.Request, write bool) (store.User, store.Repo, access.Role, bool) {
	if s.Store == nil {
		http.Error(w, s.noStorageText(r), http.StatusServiceUnavailable)
		return store.User{}, store.Repo{}, "", false
	}
	repo, err := s.Store.RepoByPath(r.Context(), r.PathValue("owner"), r.PathValue("repo"))
	if err != nil {
		http.NotFound(w, r)
		return store.User{}, store.Repo{}, "", false
	}
	token := bearer(r)
	if token == "" && !write {
		// Anoniem lezen mag alleen in een publieke repository, net als in de UI.
		if repo.Visibility != "public" {
			http.NotFound(w, r)
			return store.User{}, store.Repo{}, "", false
		}
		return store.User{}, repo, "", true
	}
	if token == "" {
		http.Error(w, s.tr(r, "err.tokenAbsent"), http.StatusUnauthorized)
		return store.User{}, store.Repo{}, "", false
	}
	if strings.HasPrefix(token, "bgj_") || !strings.HasPrefix(token, "bg_") {
		http.Error(w, s.tr(r, "err.tokenBad"), http.StatusUnauthorized)
		return store.User{}, store.Repo{}, "", false
	}
	u, err := s.Store.UserByToken(r.Context(), token)
	if err != nil {
		http.Error(w, s.tr(r, "err.tokenBad"), http.StatusUnauthorized)
		return store.User{}, store.Repo{}, "", false
	}
	role, err := s.Store.EffectiveRole(r.Context(), u.ID, repo.ID)
	if err != nil {
		http.Error(w, s.tr(r, "err.rights"), http.StatusInternalServerError)
		return store.User{}, store.Repo{}, "", false
	}
	if !role.CanRead() && repo.Visibility != "public" {
		http.NotFound(w, r)
		return store.User{}, store.Repo{}, "", false
	}
	return u, repo, role, true
}

func (s *Server) readJSON(w http.ResponseWriter, r *http.Request, dst any) bool {
	if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(dst); err != nil {
		http.Error(w, s.tr(r, "err.json"), http.StatusBadRequest)
		return false
	}
	return true
}

func (s *Server) issueJSON(repo store.Repo, iss store.Issue, notes []store.IssueNote) map[string]any {
	obj := map[string]any{
		"id": iss.Number, "title": iss.Title, "description": iss.Description,
		"status": iss.Status, "confidential": iss.Confidential, "author": iss.Author,
		"assignees": nonNil(iss.Assignees), "labels": labelNames(iss.Labels),
		"milestone": iss.Milestone, "due_date": iss.DueOn,
		"created_at": iss.CreatedAt.UTC().Format(time.RFC3339),
		"updated_at": iss.UpdatedAt.UTC().Format(time.RFC3339),
		"web_url":    strings.TrimRight(s.Cfg.BaseURL, "/") + issuePath(repo, iss.Number),
	}
	if !iss.ClosedAt.IsZero() {
		obj["closed_at"] = iss.ClosedAt.UTC().Format(time.RFC3339)
	}
	if notes != nil {
		arr := make([]any, 0, len(notes))
		for _, n := range notes {
			arr = append(arr, map[string]any{
				"id": n.ID, "author": n.Author, "body": n.Body,
				"created_at": n.CreatedAt.UTC().Format(time.RFC3339),
			})
		}
		obj["notes"] = arr
	}
	return obj
}

func nonNil(s []string) []string {
	if s == nil {
		return []string{}
	}
	return s
}
