package handlers

import (
	"context"
	"github.com/goccy/go-json"
	"madsky.ru/go-finance/internal/repository/status"
	"madsky.ru/go-finance/internal/server/request"
	"madsky.ru/go-finance/internal/server/response"
	dto "madsky.ru/go-finance/internal/status"
	"net/http"
)

func FindStatuses(ctx context.Context, repository status.Repository) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		s, err := repository.Find(ctx)
		if err != nil {
			response.Error(w, err, http.StatusBadRequest)
			return
		}

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

func FindStatusById(ctx context.Context, repository status.Repository) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		id, err := request.Param(r, "id")
		if err != nil {
			response.Error(w, err, http.StatusBadRequest)
			return
		}

		s, err := repository.FindOne(ctx, id)
		if err != nil {
			response.Error(w, err, http.StatusNotFound)
			return
		}

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

func CreateStatus(ctx context.Context, repository status.Repository) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		dec := json.NewDecoder(r.Body)
		dec.DisallowUnknownFields()

		var statusDto dto.CreateStatusDTO

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

		s, err := repository.Create(ctx, &statusDto)
		if err != nil {
			response.Error(w, err, http.StatusBadRequest)
			return
		}

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

func DeleteStatus(ctx context.Context, repository status.Repository) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		id, err := request.Param(r, "id")
		if err != nil {
			response.Error(w, err, http.StatusBadRequest)
			return
		}

		count, err := repository.Remove(ctx, id)
		if err != nil {
			response.Error(w, err, http.StatusBadRequest)
			return
		}

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