package server

import (
	"github.com/goccy/go-json"
	"madsky.ru/go-tracker/internal/model/issue"
	"madsky.ru/go-tracker/internal/server/request"
	"madsky.ru/go-tracker/internal/server/response"
	"net/http"
)

func (app *Application) findIssues(w http.ResponseWriter, _ *http.Request) {
	i, err := app.Storage.Issues.Find(app.Ctx)
	if err != nil {
		response.Error(w, err, http.StatusBadRequest)
		return
	}

	response.WriteJSON(w, nil, http.StatusOK, &i)
}

func (app *Application) findIssuesByID(w http.ResponseWriter, r *http.Request) {
	id, err := request.Param(r, "id")
	if err != nil {
		response.Error(w, err, http.StatusBadRequest)
		return
	}

	i, err := app.Storage.Issues.FindOne(app.Ctx, id)
	if err != nil {
		response.Error(w, err, http.StatusBadRequest)
		return
	}

	response.WriteJSON(w, nil, http.StatusOK, &i)
}

func (app *Application) createIssues(w http.ResponseWriter, r *http.Request) {
	dec := json.NewDecoder(r.Body)
	dec.DisallowUnknownFields()

	var issueDto issue.CreateIssueDTO

	err := dec.Decode(&issueDto)
	if err != nil {
		response.Error(w, err, http.StatusBadRequest)
		return
	}

	id, err := app.Storage.Issues.Create(app.Ctx, &issueDto)
	if err != nil {
		response.Error(w, err, http.StatusBadRequest)
		return
	}

	i, err := app.Storage.Issues.FindOne(app.Ctx, *id)
	if err != nil {
		response.Error(w, err, http.StatusBadRequest)
		return
	}

	response.WriteJSON(w, nil, http.StatusOK, &i)
}

func (app *Application) updatePositions(w http.ResponseWriter, r *http.Request) {
	dec := json.NewDecoder(r.Body)
	dec.DisallowUnknownFields()

	var positionDto issue.PositionDTO

	err := dec.Decode(&positionDto)
	if err != nil {
		response.Error(w, err, http.StatusBadRequest)
		return
	}

	i := make([]*uint32, 0)

	for position, issueId := range positionDto.Positions {
		id, err := app.Storage.Issues.UpdatePositions(app.Ctx, position, positionDto.StatusId, issueId)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		i = append(i, id)
	}

	response.WriteJSON(w, nil, http.StatusOK, &i)
}

func (app *Application) deleteIssues(w http.ResponseWriter, r *http.Request) {
	id, err := request.Param(r, "id")
	if err != nil {
		response.Error(w, err, http.StatusBadRequest)
		return
	}

	count, err := app.Storage.Issues.Remove(app.Ctx, id)
	if err != nil {
		response.Error(w, err, http.StatusBadRequest)
		return
	}

	response.WriteJSON(w, nil, http.StatusOK, count)
}
