package req

import (
	
	
	
	
	
	

	
	
)

// ErrResponseBodyTooLarge is returned when a response body exceeds the limit
// configured via Client.SetMaxResponseSize or Request.SetMaxResponseSize.
// Use errors.Is(err, ErrResponseBodyTooLarge) or errors.As with
// *ResponseBodyTooLargeError for inspection.
var ErrResponseBodyTooLarge = errors.New("req: response body too large")

// ResponseBodyTooLargeError is returned when a response body exceeds the
// configured maximum size. Limit is the configured max in bytes. ContentLength
// is the response's Content-Length when the body was rejected based on headers
// without reading; it is -1 when the limit was exceeded while reading.
type ResponseBodyTooLargeError struct {
	Limit         int64
	ContentLength int64
}

func ( *ResponseBodyTooLargeError) () string {
	if .ContentLength >= 0 {
		return fmt.Sprintf("req: response body too large: Content-Length %d exceeds limit %d", .ContentLength, .Limit)
	}
	return fmt.Sprintf("req: response body too large: exceeds limit of %d bytes", .Limit)
}

// Is reports whether target is ErrResponseBodyTooLarge.
func ( *ResponseBodyTooLargeError) ( error) bool {
	return  == ErrResponseBodyTooLarge
}

// maxResponseBodyReader limits how many bytes can be read from a response body.
// It is similar in spirit to http.MaxBytesReader but for client response bodies:
// when the limit is exceeded it returns *ResponseBodyTooLargeError and subsequent
// reads return the same sticky error. Close closes the underlying body.
type maxResponseBodyReader struct {
	r     io.ReadCloser
	n     int64 // bytes remaining
	limit int64 // original limit, for the error
	err   error // sticky error
}

func ( *maxResponseBodyReader) ( []byte) ( int,  error) {
	if .err != nil {
		return 0, .err
	}
	if len() == 0 {
		return 0, nil
	}
	// Read at most remaining+1 so we can detect crossing the limit.
	if int64(len())-1 > .n {
		 = [:.n+1]
	}
	,  = .r.Read()

	if int64() <= .n {
		.n -= int64()
		.err = 
		return , 
	}

	 = int(.n)
	.n = 0
	.err = &ResponseBodyTooLargeError{Limit: .limit, ContentLength: -1}
	return , .err
}

func ( *maxResponseBodyReader) () error {
	return .r.Close()
}

// Response is the http response.
type Response struct {
	// The underlying http.Response is embed into Response.
	*http.Response
	// Err is the underlying error, not nil if some error occurs.
	// Usually used in the ResponseMiddleware, you can skip logic in
	// ResponseMiddleware that doesn't need to be executed when err occurs.
	Err error
	// Request is the Response's related Request.
	Request    *Request
	body       []byte
	receivedAt time.Time
	error      any
	result     any
}

// IsSuccess method returns true if no error occurs and HTTP status `code >= 200 and <= 299`
// by default, you can also use Client.SetResultStateCheckFunc to customize the result
// state check logic.
//
// Deprecated: Use IsSuccessState instead.
func ( *Response) () bool {
	return .IsSuccessState()
}

// IsSuccessState method returns true if no error occurs and HTTP status `code >= 200 and <= 299`
// by default, you can also use Client.SetResultStateCheckFunc to customize the result state
// check logic.
func ( *Response) () bool {
	if .Response == nil {
		return false
	}
	return .ResultState() == SuccessState
}

// IsError method returns true if no error occurs and HTTP status `code >= 400`
// by default, you can also use Client.SetResultStateCheckFunc to customize the result
// state check logic.
//
// Deprecated: Use IsErrorState instead.
func ( *Response) () bool {
	return .IsErrorState()
}

// IsErrorState method returns true if no error occurs and HTTP status `code >= 400`
// by default, you can also use Client.SetResultStateCheckFunc to customize the result
// state check logic.
func ( *Response) () bool {
	if .Response == nil {
		return false
	}
	return .ResultState() == ErrorState
}

// GetContentType return the `Content-Type` header value.
func ( *Response) () string {
	if .Response == nil {
		return ""
	}
	return .Header.Get(header.ContentType)
}

// ResultState returns the result state.
// By default, it returns SuccessState if HTTP status `code >= 200 && code <= 299`, and returns
// ErrorState if HTTP status `code >= 400`, otherwise returns UnknownState.
// You can also use Client.SetResultStateCheckFunc to customize the result
// state check logic.
func ( *Response) () ResultState {
	if .Response == nil {
		return UnknownState
	}
	var  func( *Response) ResultState
	if .Request.client.resultStateCheckFunc != nil {
		 = .Request.client.resultStateCheckFunc
	} else {
		 = defaultResultStateChecker
	}
	return ()
}

// Result returns the automatically unmarshalled object if Request.SetSuccessResult
// is called and ResultState returns SuccessState.
// Otherwise, return nil.
//
// Deprecated: Use SuccessResult instead.
func ( *Response) () any {
	return .SuccessResult()
}

// SuccessResult returns the automatically unmarshalled object if Request.SetSuccessResult
// is called and ResultState returns SuccessState.
// Otherwise, return nil.
func ( *Response) () any {
	return .result
}

// Error returns the automatically unmarshalled object when Request.SetErrorResult
// or Client.SetCommonErrorResult is called, and ResultState returns ErrorState.
// Otherwise, return nil.
//
// Deprecated: Use ErrorResult instead.
func ( *Response) () any {
	return .error
}

// ErrorResult returns the automatically unmarshalled object when Request.SetErrorResult
// or Client.SetCommonErrorResult is called, and ResultState returns ErrorState.
// Otherwise, return nil.
func ( *Response) () any {
	return .error
}

// TraceInfo returns the TraceInfo from Request.
func ( *Response) () TraceInfo {
	return .Request.TraceInfo()
}

// TotalTime returns the total time of the request, from request we sent to response we received.
func ( *Response) () time.Duration {
	if .Request.trace != nil {
		return .Request.TraceInfo().TotalTime
	}
	if !.receivedAt.IsZero() {
		return .receivedAt.Sub(.Request.StartTime)
	}
	return .Request.responseReturnTime.Sub(.Request.StartTime)
}

// ReceivedAt returns the timestamp that response we received.
func ( *Response) () time.Time {
	return .receivedAt
}

func ( *Response) () {
	.receivedAt = time.Now()
	if .Request.trace != nil {
		.Request.trace.endTime = .receivedAt
	}
}

// UnmarshalJson unmarshalls JSON response body into the specified object.
func ( *Response) ( any) error {
	if .Err != nil {
		return .Err
	}
	,  := .ToBytes()
	if  != nil {
		return 
	}
	return .Request.client.jsonUnmarshal(, )
}

// UnmarshalXml unmarshalls XML response body into the specified object.
func ( *Response) ( any) error {
	if .Err != nil {
		return .Err
	}
	,  := .ToBytes()
	if  != nil {
		return 
	}
	return .Request.client.xmlUnmarshal(, )
}

// Unmarshal unmarshalls response body into the specified object according
// to response `Content-Type`.
func ( *Response) ( any) error {
	if .Err != nil {
		return .Err
	}
	// error by status-code
	if .IsErrorState() {
		return errors.New(.Status)
	}
	 = util.GetPointer()
	 := .Header.Get("Content-Type")
	if strings.Contains(, "json") {
		return .UnmarshalJson()
	} else if strings.Contains(, "xml") {
		return .UnmarshalXml()
	}
	return .UnmarshalJson()
}

// Into unmarshalls response body into the specified object according
// to response `Content-Type`.
func ( *Response) ( any) error {
	return .Unmarshal()
}

// Set response body with byte array content
func ( *Response) ( []byte) {
	.body = 
}

// Set response body with string content
func ( *Response) ( string) {
	.body = []byte()
}

// Bytes return the response body as []bytes that have already been read, could be
// nil if not read, the following cases are already read:
//  1. `Request.SetResult` or `Request.SetError` is called.
//  2. `Client.DisableAutoReadResponse` and `Request.DisableAutoReadResponse` is not
//     called, and also `Request.SetOutput` and `Request.SetOutputFile` is not called.
func ( *Response) () []byte {
	return .body
}

// String returns the response body as string that have already been read, could be
// nil if not read, the following cases are already read:
//  1. `Request.SetResult` or `Request.SetError` is called.
//  2. `Client.DisableAutoReadResponse` and `Request.DisableAutoReadResponse` is not
//     called, and also `Request.SetOutput` and `Request.SetOutputFile` is not called.
func ( *Response) () string {
	return string(.body)
}

// ToString returns the response body as string, read body if not have been read.
func ( *Response) () (string, error) {
	,  := .ToBytes()
	return string(), 
}

// ToBytes returns the response body as []byte, read body if not have been read.
func ( *Response) () ( []byte,  error) {
	if .Err != nil {
		return nil, .Err
	}
	if .body != nil {
		return .body, nil
	}
	if .Response == nil || .Response.Body == nil {
		return []byte{}, nil
	}
	defer func() {
		.Body.Close()
		if  != nil {
			.Err = 
		}
		.body = 
	}()
	,  = io.ReadAll(.Body)
	.setReceivedAt()
	if  == nil && .Request.client.responseBodyTransformer != nil {
		,  = .Request.client.responseBodyTransformer(, .Request, )
	}
	return
}

// Dump return the string content that have been dumped for the request.
// `Request.Dump` or `Request.DumpXXX` MUST have been called.
func ( *Response) () string {
	return .Request.getDumpBuffer().String()
}

// GetStatus returns the response status.
func ( *Response) () string {
	if .Response == nil {
		return ""
	}
	return .Status
}

// GetStatusCode returns the response status code.
func ( *Response) () int {
	if .Response == nil {
		return 0
	}
	return .StatusCode
}

// GetHeader returns the response header value by key.
func ( *Response) ( string) string {
	if .Response == nil {
		return ""
	}
	return .Header.Get()
}

// GetHeaderValues returns the response header values by key.
func ( *Response) ( string) []string {
	if .Response == nil {
		return nil
	}
	return .Header.Values()
}

// HeaderToString get all header as string.
func ( *Response) () string {
	if .Response == nil {
		return ""
	}
	return convertHeaderToString(.Header)
}