/**
 * HttpResponse - Response wrapper with utility methods
 * Provides convenient access to response status, headers, body, and parsed JSON
 */
import { ErrorFactory } from '../../exceptions/ZintrustError.js';
/**
 * Create HTTP response from fetch Response
 */
export const createHttpResponse = (response, body) => {
    const statusCode = response.status;
    const headers = Object.fromEntries(response.headers.entries());
    const lowerHeaders = Object.fromEntries(Object.entries(headers).map(([key, value]) => [key.toLowerCase(), value]));
    return {
        get status() {
            return statusCode;
        },
        get headers() {
            return headers;
        },
        get body() {
            return body;
        },
        json() {
            try {
                return JSON.parse(body);
            }
            catch (error) {
                throw ErrorFactory.createValidationError('Failed to parse JSON response', {
                    body: body.substring(0, 200), // Truncate for logging
                    error: error instanceof Error ? error.message : String(error),
                });
            }
        },
        text() {
            return body;
        },
        get ok() {
            return response.ok;
        },
        get successful() {
            return statusCode >= 200 && statusCode < 300;
        },
        get failed() {
            return !this.successful;
        },
        get serverError() {
            return statusCode >= 500;
        },
        get clientError() {
            return statusCode >= 400 && statusCode < 500;
        },
        header(name) {
            return lowerHeaders[name.toLowerCase()];
        },
        hasHeader(name) {
            return name.toLowerCase() in lowerHeaders;
        },
        throwIfServerError() {
            if (this.serverError) {
                throw ErrorFactory.createTryCatchError(`HTTP server error: ${this.status}`, {
                    status: this.status,
                    body: this.body.substring(0, 200),
                });
            }
            return this;
        },
        throwIfClientError() {
            if (this.clientError) {
                throw ErrorFactory.createTryCatchError(`HTTP client error: ${this.status}`, {
                    status: this.status,
                    body: this.body.substring(0, 200),
                });
            }
            return this;
        },
    };
};
export default {
    createHttpResponse,
};
