import type {
  HttpClient,
  HttpErrorResponse,
  HttpHeaders,
  HttpRequest,
  HttpResponse,
} from '@angular/common/http';
import type { Injector } from '@angular/core';

import type { Auth } from '../core/auth';
import type {
  ServerSentEventsOptions,
  ServerSentEventsResult,
} from '../core/serverSentEvents';
import type { Client as CoreClient, Config as CoreConfig } from '../core/types';
import type { Middleware } from './utils';

export type ResponseStyle = 'data' | 'fields';

export interface Config<T extends ClientOptions = ClientOptions>
  extends Omit<RequestInit, 'body' | 'headers' | 'method'>, Omit<CoreConfig, 'headers'> {
  /**
   * Base URL for all requests made by this client.
   */
  baseUrl?: T['baseUrl'];
  /**
   * An object containing any HTTP headers that you want to pre-populate your
   * `HttpHeaders` object with.
   *
   * {@link https://angular.dev/api/common/http/HttpHeaders#constructor See more}
   */
  headers?:
    | HttpHeaders
    | Record<
        string,
        string | number | boolean | (string | number | boolean)[] | null | undefined | unknown
      >;
  /**
   * The HTTP client to use for making requests.
   */
  httpClient?: HttpClient;
  /**
   * Should we return only data or multiple fields (data, error, response, etc.)?
   *
   * @default 'fields'
   */
  responseStyle?: ResponseStyle;

  /**
   * Throw an error instead of returning it in the response?
   *
   * @default false
   */
  throwOnError?: T['throwOnError'];
}

export interface RequestOptions<
  TData = unknown,
  TResponseStyle extends ResponseStyle = 'fields',
  ThrowOnError extends boolean = boolean,
  Url extends string = string,
>
  extends
    Config<{
      responseStyle: TResponseStyle;
      throwOnError: ThrowOnError;
    }>,
    Pick<
      ServerSentEventsOptions<TData>,
      | 'onRequest'
      | 'onSseError'
      | 'onSseEvent'
      | 'sseDefaultRetryDelay'
      | 'sseMaxRetryAttempts'
      | 'sseMaxRetryDelay'
    > {
  /**
   * Any body that you want to add to your request.
   *
   * {@link https://developer.mozilla.org/docs/Web/API/fetch#body}
   */
  body?: unknown;
  /**
   * Optional custom injector for dependency resolution if you don't implicitly or explicitly provide one.
   */
  injector?: Injector;
  path?: Record<string, unknown>;
  query?: Record<string, unknown>;
  /**
   * Security mechanism(s) to use for the request.
   */
  security?: ReadonlyArray<Auth>;
  url: Url;
}

export interface ResolvedRequestOptions<
  TResponseStyle extends ResponseStyle = 'fields',
  ThrowOnError extends boolean = boolean,
  Url extends string = string,
> extends RequestOptions<unknown, TResponseStyle, ThrowOnError, Url> {
  headers: HttpHeaders;
  serializedBody?: string;
}

export type RequestResult<
  TData = unknown,
  TError = unknown,
  ThrowOnError extends boolean = boolean,
  TResponseStyle extends ResponseStyle = 'fields',
> = Promise<
  ThrowOnError extends true
    ? TResponseStyle extends 'data'
      ? TData extends Record<string, unknown>
        ? TData[keyof TData]
        : TData
      : {
          data: TData extends Record<string, unknown> ? TData[keyof TData] : TData;
          request: HttpRequest<unknown>;
          response: HttpResponse<TData>;
        }
    : TResponseStyle extends 'data'
      ? (TData extends Record<string, unknown> ? TData[keyof TData] : TData) | undefined
      :
          | {
              data: TData extends Record<string, unknown> ? TData[keyof TData] : TData;
              error: undefined;
              request: HttpRequest<unknown>;
              response: HttpResponse<TData>;
            }
          | {
              data: undefined;
              error: TError[keyof TError];
              /** request may be undefined, because error may be from building the request object itself */
              request?: HttpRequest<unknown>;
              /** response may be undefined, because error may be from building the request object itself or from a network error */
              response?: HttpErrorResponse & {
                error: TError[keyof TError] | null;
              };
            }
>;

export interface ClientOptions {
  baseUrl?: string;
  responseStyle?: ResponseStyle;
  throwOnError?: boolean;
}

type MethodFn = <
  TData = unknown,
  TError = unknown,
  ThrowOnError extends boolean = false,
  TResponseStyle extends ResponseStyle = 'fields',
>(
  options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, 'method'>,
) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;

type SseFn = <
  TData = unknown,
  TError = unknown,
  ThrowOnError extends boolean = false,
  TResponseStyle extends ResponseStyle = 'fields',
>(
  options: Omit<RequestOptions<never, TResponseStyle, ThrowOnError>, 'method'>,
) => Promise<ServerSentEventsResult<TData, TError>>;

type RequestFn = <
  TData = unknown,
  TError = unknown,
  ThrowOnError extends boolean = false,
  TResponseStyle extends ResponseStyle = 'fields',
>(
  options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, 'method'> &
    Pick<Required<RequestOptions<TData, TResponseStyle, ThrowOnError>>, 'method'>,
) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;

type RequestOptionsFn = <
  T,
  ThrowOnError extends boolean = false,
  TResponseStyle extends ResponseStyle = 'fields',
>(
  options: RequestOptions<T, TResponseStyle, ThrowOnError>,
) => HttpRequest<T>;

type BuildUrlFn = <
  TData extends {
    body?: unknown;
    path?: Record<string, unknown>;
    query?: Record<string, unknown>;
    url: string;
  },
>(
  options: TData & Options<TData>,
) => string;

export type Client = CoreClient<RequestFn, Config, MethodFn, BuildUrlFn, SseFn> & {
  interceptors: Middleware<
    HttpRequest<unknown>,
    HttpResponse<unknown>,
    unknown,
    ResolvedRequestOptions
  >;
  requestOptions: RequestOptionsFn;
};

/**
 * The `createClientConfig()` function will be called on client initialization
 * and the returned object will become the client's initial configuration.
 *
 * You may want to initialize your client this way instead of calling
 * `setConfig()`. This is useful for example if you're using Next.js
 * to ensure your client always has the correct values.
 */
export type CreateClientConfig<T extends ClientOptions = ClientOptions> = (
  override?: Config<ClientOptions & T>,
) => Config<Required<ClientOptions> & T>;

export interface TDataShape {
  body?: unknown;
  headers?: unknown;
  path?: unknown;
  query?: unknown;
  url: string;
}

type OmitKeys<T, K> = Pick<T, Exclude<keyof T, K>>;

export type Options<
  TData extends TDataShape = TDataShape,
  ThrowOnError extends boolean = boolean,
  TResponse = unknown,
  TResponseStyle extends ResponseStyle = 'fields',
> = OmitKeys<
  RequestOptions<TResponse, TResponseStyle, ThrowOnError>,
  'body' | 'path' | 'query' | 'url'
> &
  ([TData] extends [never] ? unknown : Omit<TData, 'url'>);
