package httpx

import (
	
	
	
	
	
	

	
)

const defaultTimeout = 10 * time.Second
const defaultUserAgent = "httpx (https://github.com/goforj/httpx)"

var (
	defaultClient *Client
	defaultOnce   sync.Once
)

// Client wraps a req client with typed helpers and defaults.
// @group Client
//
// Example: create a client
//
//	c := httpx.New()
//	_ = c
type Client struct {
	req         *req.Client
	errorMapper ErrorMapperFunc
}

// New creates a client with opinionated defaults and optional overrides.
// @group Client
//
// Example: configure all client options
//
//	var buf bytes.Buffer
//	c := httpx.New(httpx.
//		BaseURL("https://api.example.com").
//		Timeout(5*time.Second).
//		Header("X-Trace", "1").
//		Headers(map[string]string{
//			"Accept": "application/json",
//		}).
//		Transport(http.RoundTripper(http.DefaultTransport)).
//		Middleware(func(_ *req.Client, r *req.Request) error {
//			r.SetHeader("X-Middleware", "1")
//			return nil
//		}).
//		ErrorMapper(func(resp *req.Response) error {
//			return fmt.Errorf("status %d", resp.StatusCode)
//		}).
//		DumpAll().
//		DumpEachRequest().
//		DumpEachRequestTo(&buf).
//		Retry(func(rc *req.Client) {
//			rc.SetCommonRetryCount(2)
//		}).
//		RetryCount(2).
//		RetryFixedInterval(200 * time.Millisecond).
//		RetryBackoff(100*time.Millisecond, 2*time.Second).
//		RetryInterval(func(_ *req.Response, attempt int) time.Duration {
//			return time.Duration(attempt) * 100 * time.Millisecond
//		}).
//		RetryCondition(func(resp *req.Response, _ error) bool {
//			return resp != nil && resp.StatusCode == 503
//		}).
//		RetryHook(func(_ *req.Response, _ error) {}),
//	)
//	_ = c
func ( ...Option) *Client {
	 := &Client{
		req: req.C().SetTimeout(defaultTimeout).SetUserAgent(defaultUserAgent),
	}
	for ,  := range  {
		if  == nil {
			continue
		}
		.applyClient()
	}
	if ,  := os.LookupEnv("HTTP_TRACE");  {
		.req.EnableDumpAll()
	}
	return 
}

// Default returns the shared default client.
// @group Client
//
// Example: use default client for quick calls
//
//	c := httpx.Default()
//	_ = c
func () *Client {
	defaultOnce.Do(func() {
		defaultClient = New()
	})
	return defaultClient
}

// Req returns the underlying req client for advanced usage.
// @group Client
//
// Example: enable req debugging
//
//	c := httpx.New()
//	c.Req().EnableDumpEachRequest()
func ( *Client) () *req.Client {
	return .req
}

// Raw returns the underlying req client for chaining raw requests.
// @group Client
//
// Example: drop down to req
//
//	c := httpx.New()
//	resp, err := c.Raw().R().Get("https://httpbin.org/uuid")
//	_, _ = resp, err
func ( *Client) () *req.Client {
	return .req
}

// Get issues a GET request using the provided client.
// @group Requests
//
// Example: fetch GitHub pull requests (typed)
//
//	type PullRequest struct {
//		Number int    `json:"number"`
//		Title  string `json:"title"`
//	}
//
//	c := httpx.New(httpx.Header("Accept", "application/vnd.github+json"))
//	res := httpx.Get[[]PullRequest](c, "https://api.github.com/repos/goforj/httpx/pulls")
//	if res.Err != nil {
//		return
//	}
//	godump.Dump(res.Body)
//
// Example: bind to a string body
//
//	c2 := httpx.New()
//	res2 := httpx.Get[string](c2, "https://httpbin.org/uuid")
//	_, _ = res2.Body, res2.Err // Body is string
func [ any]( *Client,  string,  ...Option) Result[] {
	return do[](, nil, methodGet, , nil, )
}

// Post issues a POST request using the provided client.
// @group Requests
//
// Example: typed POST
//
//	type CreateUser struct {
//		Name string `json:"name"`
//	}
//	type User struct {
//		Name string `json:"name"`
//	}
//
//	c := httpx.New()
//	res := httpx.Post[CreateUser, User](c, "https://api.example.com/users", CreateUser{Name: "Ana"})
//	_, _ = res.Body, res.Err // Body is User
func [ any,  any]( *Client,  string,  ,  ...Option) Result[] {
	return do[](, nil, methodPost, , , )
}

// Put issues a PUT request using the provided client.
// @group Requests
//
// Example: typed PUT
//
//	type UpdateUser struct {
//		Name string `json:"name"`
//	}
//	type User struct {
//		Name string `json:"name"`
//	}
//
//	c := httpx.New()
//	res := httpx.Put[UpdateUser, User](c, "https://api.example.com/users/1", UpdateUser{Name: "Ana"})
//	_, _ = res.Body, res.Err // Body is User
func [ any,  any]( *Client,  string,  ,  ...Option) Result[] {
	return do[](, nil, methodPut, , , )
}

// Patch issues a PATCH request using the provided client.
// @group Requests
//
// Example: typed PATCH
//
//	type UpdateUser struct {
//		Name string `json:"name"`
//	}
//	type User struct {
//		Name string `json:"name"`
//	}
//
//	c := httpx.New()
//	res := httpx.Patch[UpdateUser, User](c, "https://api.example.com/users/1", UpdateUser{Name: "Ana"})
//	_, _ = res.Body, res.Err // Body is User
func [ any,  any]( *Client,  string,  ,  ...Option) Result[] {
	return do[](, nil, methodPatch, , , )
}

// Delete issues a DELETE request using the provided client.
// @group Requests
//
// Example: typed DELETE
//
//	type DeleteResponse struct {
//		OK bool `json:"ok"`
//	}
//
//	c := httpx.New()
//	res := httpx.Delete[DeleteResponse](c, "https://api.example.com/users/1")
//	_, _ = res.Body, res.Err // Body is DeleteResponse
func [ any]( *Client,  string,  ...Option) Result[] {
	return do[](, nil, methodDelete, , nil, )
}

// Head issues a HEAD request using the provided client.
// @group Requests
//
// Example: HEAD request
//
//	c := httpx.New()
//	res := httpx.Head[string](c, "https://example.com")
//	_ = res
func [ any]( *Client,  string,  ...Option) Result[] {
	return do[](, nil, methodHead, , nil, )
}

// Options issues an OPTIONS request using the provided client.
// @group Requests
//
// Example: OPTIONS request
//
//	c := httpx.New()
//	res := httpx.Options[string](c, "https://example.com")
//	_ = res
func [ any]( *Client,  string,  ...Option) Result[] {
	return do[](, nil, methodOptions, , nil, )
}

// GetCtx issues a GET request using the provided client and context.
// @group Requests (Context)
//
// Example: context-aware GET
//
//	type User struct {
//		Name string `json:"name"`
//	}
//
//	c := httpx.New()
//	ctx := context.Background()
//	res := httpx.GetCtx[User](c, ctx, "https://api.example.com/users/1")
//	_, _ = res.Body, res.Err // Body is User
func [ any]( *Client,  context.Context,  string,  ...Option) Result[] {
	return do[](, , methodGet, , nil, )
}

// PostCtx issues a POST request using the provided client and context.
// @group Requests (Context)
//
// Example: context-aware POST
//
//	type CreateUser struct {
//		Name string `json:"name"`
//	}
//	type User struct {
//		Name string `json:"name"`
//	}
//
//	c := httpx.New()
//	ctx := context.Background()
//	res := httpx.PostCtx[CreateUser, User](c, ctx, "https://api.example.com/users", CreateUser{Name: "Ana"})
//	_, _ = res.Body, res.Err // Body is User
func [ any,  any]( *Client,  context.Context,  string,  ,  ...Option) Result[] {
	return do[](, , methodPost, , , )
}

// PutCtx issues a PUT request using the provided client and context.
// @group Requests (Context)
//
// Example: context-aware PUT
//
//	type UpdateUser struct {
//		Name string `json:"name"`
//	}
//	type User struct {
//		Name string `json:"name"`
//	}
//
//	c := httpx.New()
//	ctx := context.Background()
//	res := httpx.PutCtx[UpdateUser, User](c, ctx, "https://api.example.com/users/1", UpdateUser{Name: "Ana"})
//	_, _ = res.Body, res.Err // Body is User
func [ any,  any]( *Client,  context.Context,  string,  ,  ...Option) Result[] {
	return do[](, , methodPut, , , )
}

// PatchCtx issues a PATCH request using the provided client and context.
// @group Requests (Context)
//
// Example: context-aware PATCH
//
//	type UpdateUser struct {
//		Name string `json:"name"`
//	}
//	type User struct {
//		Name string `json:"name"`
//	}
//
//	c := httpx.New()
//	ctx := context.Background()
//	res := httpx.PatchCtx[UpdateUser, User](c, ctx, "https://api.example.com/users/1", UpdateUser{Name: "Ana"})
//	_, _ = res.Body, res.Err // Body is User
func [ any,  any]( *Client,  context.Context,  string,  ,  ...Option) Result[] {
	return do[](, , methodPatch, , , )
}

// DeleteCtx issues a DELETE request using the provided client and context.
// @group Requests (Context)
//
// Example: context-aware DELETE
//
//	type DeleteResponse struct {
//		OK bool `json:"ok"`
//	}
//
//	c := httpx.New()
//	ctx := context.Background()
//	res := httpx.DeleteCtx[DeleteResponse](c, ctx, "https://api.example.com/users/1")
//	_, _ = res.Body, res.Err // Body is DeleteResponse
func [ any]( *Client,  context.Context,  string,  ...Option) Result[] {
	return do[](, , methodDelete, , nil, )
}

// HeadCtx issues a HEAD request using the provided client and context.
// @group Requests (Context)
//
// Example: context-aware HEAD
//
//	c := httpx.New()
//	ctx := context.Background()
//	res := httpx.HeadCtx[string](c, ctx, "https://example.com")
//	_ = res
func [ any]( *Client,  context.Context,  string,  ...Option) Result[] {
	return do[](, , methodHead, , nil, )
}

// OptionsCtx issues an OPTIONS request using the provided client and context.
// @group Requests (Context)
//
// Example: context-aware OPTIONS
//
//	c := httpx.New()
//	ctx := context.Background()
//	res := httpx.OptionsCtx[string](c, ctx, "https://example.com")
//	_ = res
func [ any]( *Client,  context.Context,  string,  ...Option) Result[] {
	return do[](, , methodOptions, , nil, )
}

func do[ any]( *Client,  context.Context, ,  string,  any,  []Option) Result[] {
	var  Result[]

	if  == nil {
		 = Default()
	}
	 := .req.R()
	if  != nil {
		.SetContext()
	}
	if  != nil {
		setBody(, )
	}
	for ,  := range  {
		if  == nil {
			continue
		}
		.applyRequest()
	}

	 := rawKindOf[]()
	if  == rawNone {
		.SetSuccessResult(&.Body)
	}

	,  := send(, , )
	if  != nil {
		if  != nil && .IsSuccessState() &&  == rawNone && isEmptyBody() {
			ensureNonNil(&.Body)
			.Response = 
			return 
		}
		.Err = 
		.Response = 
		return 
	}
	if .IsSuccessState() {
		if  != rawNone {
			.Body = decodeRaw[]()
		}
		if  == rawNone {
			ensureNonNil(&.Body)
		}
		.Response = 
		return 
	}

	.Response = 
	.Err = .mapError()
	return 
}

func ( *Client) ( *req.Response) error {
	if .errorMapper != nil {
		return .errorMapper()
	}
	return newHTTPError()
}

const (
	methodGet     = "GET"
	methodPost    = "POST"
	methodPut     = "PUT"
	methodPatch   = "PATCH"
	methodDelete  = "DELETE"
	methodHead    = "HEAD"
	methodOptions = "OPTIONS"
)

func send( *req.Request, ,  string) (*req.Response, error) {
	switch  {
	case methodGet:
		return .Get()
	case methodPost:
		return .Post()
	case methodPut:
		return .Put()
	case methodPatch:
		return .Patch()
	case methodDelete:
		return .Delete()
	case methodHead:
		return .Head()
	case methodOptions:
		return .Options()
	default:
		return nil, fmt.Errorf("httpx: unsupported method %s", )
	}
}

// dumpExample is a no-op wrapper to keep the godump import live for doc examples.
func dumpExample( ...interface{}) {
	godump.Dump(...)
}