/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */

import type Protocol from 'devtools-protocol';

import type {SecurityDetails} from '../common/SecurityDetails.js';

import type {Frame} from './Frame.js';
import type {HTTPRequest} from './HTTPRequest.js';

/**
 * @public
 */
export interface RemoteAddress {
  ip?: string;
  port?: number;
}

/**
 * The HTTPResponse class represents responses which are received by the
 * {@link Page} class.
 *
 * @public
 */
export abstract class HTTPResponse {
  /**
   * @internal
   */
  constructor() {}

  /**
   * The IP address and port number used to connect to the remote
   * server.
   */
  abstract remoteAddress(): RemoteAddress;

  /**
   * The URL of the response.
   */
  abstract url(): string;

  /**
   * True if the response was successful (status in the range 200-299).
   */
  ok(): boolean {
    // TODO: document === 0 case?
    const status = this.status();
    return status === 0 || (status >= 200 && status <= 299);
  }

  /**
   * The status code of the response (e.g., 200 for a success).
   */
  abstract status(): number;

  /**
   * The status text of the response (e.g. usually an "OK" for a
   * success).
   */
  abstract statusText(): string;

  /**
   * An object with HTTP headers associated with the response. All header names
   * are lower-case. Duplicate header values are combined into a single
   * comma-separated list except for `Set-Cookie` that is separated by `\n`.
   */
  abstract headers(): Record<string, string>;

  /**
   * {@link SecurityDetails} if the response was received over the
   * secure connection, or `null` otherwise.
   */
  abstract securityDetails(): SecurityDetails | null;

  /**
   * Timing information related to the response.
   */
  abstract timing(): Protocol.Network.ResourceTiming | null;

  /**
   * Promise which resolves to a buffer with response body.
   *
   * @remarks
   *
   * The buffer might be re-encoded by the browser
   * based on HTTP-headers or other heuristics. If the browser
   * failed to detect the correct encoding, the buffer might
   * be encoded incorrectly. See
   * https://github.com/puppeteer/puppeteer/issues/6478.
   */
  abstract content(): Promise<Uint8Array>;

  /**
   * {@inheritDoc HTTPResponse.content}
   */
  async buffer(): Promise<Buffer> {
    const content = await this.content();
    return Buffer.from(content);
  }
  /**
   * Promise which resolves to a text (utf8) representation of response body.
   *
   * @remarks
   *
   * This method will throw if the content is not utf-8 string
   */
  async text(): Promise<string> {
    const content = await this.content();
    return new TextDecoder('utf-8', {fatal: true}).decode(content);
  }

  /**
   * Promise which resolves to a JSON representation of response body.
   *
   * @remarks
   *
   * This method will throw if the response body is not parsable via
   * `JSON.parse`.
   */
  async json(): Promise<any> {
    const content = await this.text();
    return JSON.parse(content);
  }

  /**
   * Converts the response to a Fetch API Response instance.
   *
   * @remarks
   *
   * Headers are copied to the new Response instance, with multi-line
   * `set-cookie` headers parsed into individual header entries.
   * For responses with null body statuses (101, 204, 205, 304), the body is
   * omitted.
   *
   * @returns A promise which resolves to a Fetch API Response object.
   */
  async asFetchResponse(): Promise<Response> {
    const headers = new Headers();
    for (const [key, value] of Object.entries(this.headers())) {
      if (key === 'set-cookie') {
        for (const cookie of value.split('\n')) {
          const trimmed = cookie.trim();
          if (trimmed) {
            headers.append(key, trimmed);
          }
        }
      } else {
        headers.append(key, value);
      }
    }

    const status = this.status();
    const isNullBodyStatus =
      status === 101 || status === 204 || status === 205 || status === 304;
    const body = isNullBodyStatus
      ? null
      : ((await this.content()) as unknown as BodyInit);

    return new Response(body, {
      status,
      statusText: this.statusText(),
      headers,
    });
  }

  /**
   * A matching {@link HTTPRequest} object.
   */
  abstract request(): HTTPRequest;

  /**
   * True if the response was served from either the browser's disk
   * cache or memory cache.
   */
  abstract fromCache(): boolean;

  /**
   * True if the response was served by a service worker.
   */
  abstract fromServiceWorker(): boolean;

  /**
   * A {@link Frame} that initiated this response, or `null` if
   * navigating to error pages.
   */
  abstract frame(): Frame | null;
}
