import type { IDAgent } from './agent/index.js';
import type { DidResolutionOptions, DidResolutionResult } from './dids/index.js';

import { DidMessage } from './agent/did-manager.js';

import type { DidService } from './dids/types.js';

import { DidIonMethod } from './dids/index.js';
import { getServiceDwnEndpoints } from './service-options.js';

import { getServices, isDwnServiceEndpoint } from './dids/utils.js';

export type CustomServiceOptions = {
  serviceOptions?: {
    dwnEndpoints?: string[]
  },
}

/**
 * The DID API is used to create and resolve DIDs.
 *
 * @beta
 */
export class DidApi {
  private agent: IDAgent;
  private connectedDid: string;
  didUtils: any;

  constructor(options: { agent: IDAgent, connectedDid: string }) {
    this.agent = options.agent;
    this.connectedDid = options.connectedDid;
    this.didUtils = { getServices, isDwnServiceEndpoint };
  }

  /**
   * Resolves a DID to a DID Resolution Result.
   *
   * @param didUrl - The DID or DID URL to resolve.
   * @returns A promise that resolves to the DID Resolution Result.
   */
  async resolve(didUrl: string, resolutionOptions?: DidResolutionOptions): Promise<DidResolutionResult> {
    const agentResponse = await this.agent.processDidRequest({
      messageOptions : { didUrl, resolutionOptions },
      messageType    : DidMessage.Resolve
    });

    const { result } = agentResponse;

    return result as DidResolutionResult;
  }

  /**
   * Resolves a DID to a DID Resolution Result.
   *
   * @param options - custom service options
   * @returns A promise that resolves to the DID Resolution Result.
   */
  async create(options: CustomServiceOptions = {}): Promise<any> {
    const services: DidService[] = [{
      id              : '#dwn',
      type            : 'DecentralizedWebNode',
      serviceEndpoint : {
        nodes: options?.serviceOptions?.dwnEndpoints ? options?.serviceOptions?.dwnEndpoints : await getServiceDwnEndpoints()
      }
    }];

    return await DidIonMethod.create({
      services,
    });
  }

}