package photosapi

import (
	"errors"
	"fmt"
	"strings"

	"github.com/gin-gonic/gin"
)

var (
	ErrReqMissingBody = errors.New("missing body")
)

type ErrorWithDetails struct {
	Err     string   `json:"error"`
	Details []string `json:"details"`
}

func (u *ErrorWithDetails) Error() string {
	if len(u.Details) == 0 {
		return u.Err
	}
	return fmt.Sprintf("%s: \n    - %s", u.Err, strings.Join(u.Details, "\n    - "))
}

func (s *Service) HandleError(c *gin.Context) {
	c.Next()
	err := c.Errors.Last()
	if err == nil {
		return
	}

	errWithDetails := &ErrorWithDetails{err.Error(), nil}

	if errWithDetails.Err == "EOF" {
		errWithDetails.Err = "missing body"
	}

	if err.Type == gin.ErrorTypeBind {
		errWithDetails.Err, errWithDetails.Details = "binding error", strings.Split(errWithDetails.Err, "\n")
	}

	c.JSON(-1, errWithDetails)
}