package internal

import (
	"encoding/json"
	"net/http"
	"strconv"

	"github.com/go-chi/chi"
)

func (a *adminHandler) createRule(r *http.Request) (*RestResponse, error) {
	var rr RuleRow

	if err := json.NewDecoder(r.Body).Decode(&rr); err != nil {
		return ErrorResponse(http.StatusUnprocessableEntity, err), nil
	}

	if err := a.Storage.AddRule(rr); err != nil {
		return nil, err
	}

	return BasicResponse(true, nil), nil
}

func (a *adminHandler) getRule(r *http.Request) (*RestResponse, error) {
	ruleIdParam := chi.URLParam(r, "id")
	ruleId, err := strconv.Atoi(ruleIdParam)
	if err != nil {
		return BasicResponse(false, "`id` must be a valid integer."), nil
	}

	results, err := a.Storage.GetRule(ruleId)
	if err != nil {
		return nil, err
	}

	return BasicResponse(true, results), nil
}

func (a *adminHandler) getRules(r *http.Request) (*RestResponse, error) {
	results, err := a.Storage.GetRules()
	if err != nil {
		return nil, err
	}

	if len(results) <= 0 {
		results = []RuleRow{}
	}

	return BasicResponse(true, results), nil
}

func (a *adminHandler) deleteRule(r *http.Request) (*RestResponse, error) {
	ruleIdParam := chi.URLParam(r, "id")
	ruleId, err := strconv.Atoi(ruleIdParam)
	if err != nil {
		return BasicResponse(false, "`id` must be a valid integer"), nil
	}

	if err := a.Storage.DeleteRule(ruleId); err != nil {
		return nil, err
	}

	rule, err := a.Storage.GetRule(ruleId)
	if err != nil {
		return nil, err
	}

	return BasicResponse(true, rule), nil
}

func (a *adminHandler) updateRule(r *http.Request) (*RestResponse, error) {
	var rr RuleRow

	if err := json.NewDecoder(r.Body).Decode(&rr); err != nil {
		return ErrorResponse(http.StatusUnprocessableEntity, err), nil
	}

	if err := a.UpdateRule(rr.ID, rr); err != nil {
		return nil, err
	}

	rule, err := a.GetRule(rr.ID)
	if err != nil {
		return nil, err
	}

	return BasicResponse(true, rule), nil
}
