import { Injectable, inject } from '@angular/core';

import { resolveMobileAdapter } from '../logic/mobile-capacitor-adapter.rules';
import type { MobileCallKitAdapter } from '../contracts/mobile.contracts';
import { WebMobileCallKitAdapter } from '../adapters/web/web-mobile-callkit.adapter';
import { MobilePlatformService } from './mobile-platform.service';

/** Facade for iOS CallKit active-call reporting. */
@Injectable({ providedIn: 'root' })
export class MobileCallKitService {
  private readonly mobilePlatform = inject(MobilePlatformService);
  private adapter: MobileCallKitAdapter = new WebMobileCallKitAdapter();
  private adapterReady: Promise<MobileCallKitAdapter> | null = null;

  startActiveCall(callId: string, displayName: string): Promise<void> {
    if (!this.mobilePlatform.isCapacitor()) {
      return Promise.resolve();
    }

    return this.ensureAdapter().then((adapter) => adapter.startActiveCall(callId, displayName));
  }

  endActiveCall(callId: string): Promise<void> {
    if (!this.mobilePlatform.isCapacitor()) {
      return Promise.resolve();
    }

    return this.ensureAdapter().then((adapter) => adapter.endActiveCall(callId));
  }

  private ensureAdapter(): Promise<MobileCallKitAdapter> {
    if (!this.adapterReady) {
      this.adapterReady = resolveMobileAdapter(
        this.mobilePlatform.runtime(),
        this.adapter,
        async () => {
          const { CapacitorMobileCallKitAdapter } = await import('../adapters/capacitor/capacitor-mobile-callkit.adapter');

          return new CapacitorMobileCallKitAdapter();
        }
      ).then((adapter) => {
        this.adapter = adapter;
        return adapter;
      });
    }

    return this.adapterReady;
  }
}
