package errorutil

import (
	"errors"
	"net/http"

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

var (
	ErrBotNotFound        = errors.New("Bot not found")
	ErrBotAlreadyExists   = errors.New("This bot has already been submitted")
	ErrSearchFailed       = errors.New("No bots found fitting this filter")
	ErrMainOwnerAsCoOwner = errors.New("You cannot set yourself as a co-owner")
	ErrBotNotExists       = errors.New("Bot does not exist inside Discord")

	// validation
	ErrInvalidID       = errors.New("Invalid Discord id")
	ErrInvalidOverview = errors.New("Bot overview must be between 15 and 50 characters long")
)

type ErrResponse struct {
	Err            error  `json:"-"`
	HTTPStatusCode int    `json:"-"`
	StatusText     string `json:"status"`
	ErrorText      string `json:"error,omitempty"`
}

func (e *ErrResponse) Render(w http.ResponseWriter, r *http.Request) error {
	render.Status(r, e.HTTPStatusCode)
	return nil
}

func ErrInvalidRequest(err error) render.Renderer {
	return &ErrResponse{
		Err:            err,
		HTTPStatusCode: 400,
		StatusText:     "invalid request",
		ErrorText:      errString(err),
	}
}

func ErrInternal(err error) render.Renderer {
	return &ErrResponse{
		Err:            err,
		HTTPStatusCode: 500,
		StatusText:     "internal server error",
		ErrorText:      errString(err),
	}
}

var ErrNotFound = &ErrResponse{
	HTTPStatusCode: 404,
	StatusText:     "resource not found",
}

var ErrUnauthorized = &ErrResponse{
	HTTPStatusCode: 401,
	StatusText:     "unauthorized",
}

var ErrForbidden = &ErrResponse{
	HTTPStatusCode: 403,
	StatusText:     "forbidden",
}

func errString(err error) string {
	if err == nil {
		return ""
	}
	return err.Error()
}
