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

import { resolveMobileAdapter } from '../logic/mobile-capacitor-adapter.rules';
import type { MobileAppLifecycleAdapter } from '../contracts/mobile.contracts';
import { WebMobileAppLifecycleAdapter } from '../adapters/web/web-mobile-app-lifecycle.adapter';
import { MobilePlatformService } from './mobile-platform.service';

/** Facade for foreground/background lifecycle events. */
@Injectable({ providedIn: 'root' })
export class MobileAppLifecycleService {
  private readonly mobilePlatform = inject(MobilePlatformService);
  private adapter: MobileAppLifecycleAdapter = new WebMobileAppLifecycleAdapter();
  private adapterReady: Promise<MobileAppLifecycleAdapter> | null = null;
  private initialized = false;

  async initialize(): Promise<void> {
    if (this.initialized) {
      return;
    }

    const adapter = await this.ensureAdapter();

    await adapter.initialize();
    this.mobilePlatform.refreshRuntimeDetection();
    this.initialized = true;
  }

  onAppStateChange(handler: (isActive: boolean) => void): void {
    this.adapter.onAppStateChange(handler);
  }

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

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

    return this.adapterReady;
  }
}
