import { IProjectRunnerOptions } from '../runtime/node/InteropInterfaces.js'
import { Kind as HttpProjectKind, HttpProject, IHttpProject } from '../models/HttpProject.js'
import { ApiError } from '../runtime/store/Errors.js'
import { StoreSdk } from '../runtime/store/StoreSdkNode.js'
import { ProjectSerialRunner } from '../runtime/node/ProjectSerialRunner.js'
import { ProjectParallelRunner } from '../runtime/node/ProjectParallelRunner.js'
import Proxy, { IProxyResult } from './Proxy.js'
import { IProjectExecutionLog } from '../models/ProjectExecution.js'

interface ProxyInit {
  kind: typeof HttpProjectKind
  /**
   * Runner options.
   */
  options: IProjectRunnerOptions
  /**
   * A signal to be sent to the proxy bindings to abort the request on demand.
   */
  signal?: AbortSignal | null
}

export interface IHttpProjectProxyInit extends ProxyInit {
  project: IHttpProject
}

export interface IHttpProjectStoreProxyInit extends ProxyInit {
  kind: typeof HttpProjectKind
  /**
   * Project key
   */
  pid: string
  /**
   * The parent organization key.
   */
  organization: string
}

/**
 * Runs requests from an HTTP project read from the store.
 */
export default class HttpProjectProxy extends Proxy {
  project?: HttpProject
  options?: IProjectRunnerOptions

  protected async configureStore(init: IHttpProjectStoreProxyInit, token: string, baseUri: string): Promise<void> {
    const { pid, options, organization } = init
    if (!pid) {
      throw new ApiError({
        error: true,
        message: 'Invalid request',
        detail: 'The "pid" parameter is required.',
        code: 400,
      })
    }
    if (!organization) {
      throw new ApiError({
        error: true,
        message: 'Invalid request',
        detail: 'The "organization" parameter is required.',
        code: 400,
      })
    }
    if (!options) {
      throw new ApiError({
        error: true,
        message: 'Invalid request',
        detail: 'The "options" parameter is required.',
        code: 400,
      })
    }
    if (!token) {
      throw new ApiError({
        error: true,
        message: 'Invalid request',
        detail: 'Set the authentication credentials.',
        code: 400,
      })
    }
    if (!baseUri) {
      throw new ApiError({
        error: true,
        message: 'Invalid request',
        detail: 'The store uri is missing.',
        code: 400,
      })
    }
    if (!baseUri.startsWith('http')) {
      throw new ApiError({
        error: true,
        message: 'Invalid request',
        detail: 'The store uri is invalid.',
        code: 400,
      })
    }
    const sdk = new StoreSdk(baseUri)
    sdk.token = token
    let project: IHttpProject
    try {
      const data = await sdk.file.readMedia(organization, pid)
      project = data.media as IHttpProject
    } catch (cause) {
      const e = cause as Error
      throw new ApiError(e.message, 400)
    }
    if (project.key !== pid) {
      throw new ApiError(`Unable to read the project.`, 500)
    }
    this.options = options
    this.project = new HttpProject(project)
  }

  protected async configureProject(init: IHttpProjectProxyInit): Promise<void> {
    const { project, options } = init
    if (!options) {
      throw new ApiError({
        error: true,
        message: 'Invalid request',
        detail: 'The "options" parameter is required.',
        code: 400,
      })
    }
    if (!project) {
      throw new ApiError({
        error: true,
        message: 'Invalid request',
        detail: 'The "project" parameter is required.',
        code: 400,
      })
    }
    this.options = options
    this.project = new HttpProject(project)
  }

  async configure(
    init: IHttpProjectProxyInit | IHttpProjectStoreProxyInit,
    token?: string,
    baseUri?: string
  ): Promise<void> {
    const typedStore = init as IHttpProjectStoreProxyInit
    if (typeof typedStore.pid === 'string') {
      return this.configureStore(typedStore, token as string, baseUri as string)
    }
    const typedProject = init as IHttpProjectProxyInit
    return this.configureProject(typedProject)
  }

  async execute(): Promise<IProxyResult<IProjectExecutionLog>> {
    const project = this.project as HttpProject
    const opts = this.options as IProjectRunnerOptions
    let factory: ProjectParallelRunner | ProjectSerialRunner
    if (opts.parallel) {
      factory = new ProjectParallelRunner(project, opts)
    } else {
      factory = new ProjectSerialRunner()
      factory.configure(project, opts)
    }

    function unhandledRejection(): void {
      //
    }
    // the executing library handles all related errors it need.
    // However, when executing a request to an unknown host Node process may
    // throw unhandled error event when the error is properly reported by the
    // application. This suppresses these errors.
    // Note, uncomment this line for debug.
    process.on('unhandledRejection', unhandledRejection)
    const report = await factory.execute()
    process.off('unhandledRejection', unhandledRejection)
    return {
      result: report,
    }
  }
}
