package examples

import (
	"errors"
	"fmt"
	"strconv"
)

// Sentinel error: compare with errors.Is.
var ErrNotFound = errors.New("not found")

// Custom error type: inspect with errors.As.
type ValidationError struct {
	Field string
	Msg   string
}

func (e *ValidationError) Error() string { return e.Field + ": " + e.Msg }

var users = map[int]string{1: "ada", 2: "linus"}

func FindUser(id int) (string, error) {
	if id <= 0 {
		return "", &ValidationError{Field: "id", Msg: "must be positive"}
	}
	name, ok := users[id]
	if !ok {
		// %w wraps: the chain keeps ErrNotFound for errors.Is
		return "", fmt.Errorf("find user %d: %w", id, ErrNotFound)
	}
	return name, nil
}

// ParsePort shows wrapping a standard-library error.
func ParsePort(s string) (int, error) {
	n, err := strconv.Atoi(s)
	if err != nil {
		return 0, fmt.Errorf("parse port %q: %w", s, err)
	}
	if n < 1 || n > 65535 {
		return 0, &ValidationError{Field: "port", Msg: "out of range"}
	}
	return n, nil
}

// SafeDivide converts a panic into an error with recover.
func SafeDivide(a, b int) (q int, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("recovered: %v", r)
		}
	}()
	return a / b, nil
}
