// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

import * as coreClient from "@azure/core-client"; // External library import
import {
  createPipelineRequest,
  createHttpHeaders,
  createDefaultHttpClient,
  HttpClient,
} from "@azure/core-rest-pipeline"; // Grouped imports from the same module

import { CommunicationTokenCredential, SignalingClientOptions } from "./SignalingClient"; // Local imports
import { CONFIG_API_VERSION, PACKAGE_VERSION } from "./constants";

export class TrouterConfigClient extends coreClient.ServiceClient {
  private endpoint: string;
  public apiVersion: string;
  private httpClient: HttpClient;

  constructor(endpoint: string, options?: SignalingClientOptions) {
    // Initializing default values for options
    if (!options) {
      options = {};
    }

    const packageDetails = `azsdk-js-communication-signaling/${PACKAGE_VERSION}`;
    const userAgentPrefix =
      options.userAgentOptions && options.userAgentOptions.userAgentPrefix
        ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`
        : `${packageDetails}`;

    const clientOptions = {
      ...options,
      userAgentOptions: {
        userAgentPrefix,
      },
      additionalPolicies: options.additionalPolicies,
    };
    super(clientOptions);
    this.apiVersion = CONFIG_API_VERSION;
    this.endpoint = endpoint;
    this.httpClient = createDefaultHttpClient();
  }

  async fetchServiceUrls(
    credential: CommunicationTokenCredential
  ): Promise<RealTimeNotificationConfiguration> {
    try {
      const token = (await credential.getToken()).token;

      const request = createPipelineRequest({
        url: `${this.endpoint}/chat/config/realTimeNotifications?api-version=${this.apiVersion}`,
        method: "GET",
        headers: createHttpHeaders({
          Authorization: `Bearer ${token}`,
        }),
      });

      const response = await this.pipeline.sendRequest(this.httpClient, request);

      if (response.status !== 200 || !response.bodyAsText) {
        throw new Error(
          `Failed to fetch service URLs. Status: ${response.status}, Body: ${
            response.bodyAsText || "No response body"
          }`
        );
      }

      const data = JSON.parse(response.bodyAsText);

      // Ensure all necessary data fields are present
      if (!data.trouterServiceUrl || !data.registrarServiceUrl || !data.cloudType) {
        throw new Error("One or more required fields are missing in the response data");
      }

      return new RealTimeNotificationConfiguration(
        data.trouterServiceUrl,
        data.registrarServiceUrl,
        data.cloudType
      );
    } catch (error) {
      throw new Error(
        `Error fetching real-time notification configuration from Chat Gateway: ${error.message}`
      );
    }
  }
}

export class RealTimeNotificationConfiguration {
  public trouterServiceUrl: string;
  public registrarServiceUrl: string;
  public cloudType: string;

  constructor(trouterServiceUrl: string, registrarServiceUrl: string, cloudType: string) {
    this.trouterServiceUrl = trouterServiceUrl;
    this.registrarServiceUrl = registrarServiceUrl;
    this.cloudType = cloudType;
  }
}
