package regionalservice

import (
	"errors"
	"fmt"
	"net/http"

	"github.com/tidbcloud/ticdc-service-ng/pkg/util"
)

// NotFoundError indicates a semantic not found (e.g. 200 OK with empty results).
type NotFoundError struct {
	Resource string
	ID       string
	Msg      string
}

func (e *NotFoundError) Error() string {
	if e == nil {
		return "<nil>"
	}
	if e.Msg != "" {
		return e.Msg
	}
	if e.Resource != "" && e.ID != "" {
		return fmt.Sprintf("%s %s not found", e.Resource, e.ID)
	}
	if e.Resource != "" {
		return fmt.Sprintf("%s not found", e.Resource)
	}
	return "not found"
}

// IsNotFound returns true if the error indicates a not found condition.
func IsNotFound(err error) bool {
	if err == nil {
		return false
	}

	var statusErr *util.StatusError
	if errors.As(err, &statusErr) {
		return statusErr.StatusCode == http.StatusNotFound
	}
	var notFoundErr *NotFoundError
	return errors.As(err, &notFoundErr)
}
