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

import { resolveMobileAdapter } from '../logic/mobile-capacitor-adapter.rules';
import type { MobilePersistenceAdapter } from '../contracts/mobile.contracts';
import { WebMobilePersistenceAdapter } from '../adapters/web/web-mobile-persistence.adapter';
import { MobilePlatformService } from './mobile-platform.service';
import { MobileSqliteConnectionService } from './mobile-sqlite-connection.service';

/** Facade for native SQLite persistence on mobile shells. */
@Injectable({ providedIn: 'root' })
export class MobilePersistenceService {
  private readonly mobilePlatform = inject(MobilePlatformService);
  private readonly sqliteConnection = inject(MobileSqliteConnectionService);
  private adapter: MobilePersistenceAdapter = new WebMobilePersistenceAdapter();
  private adapterReady: Promise<MobilePersistenceAdapter> | null = null;

  get isNativeSqlite(): boolean {
    return this.adapter.isNativeSqlite;
  }

  initialize(): Promise<void> {
    return this.ensureAdapter().then((adapter) => adapter.initialize());
  }

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

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

    return this.adapterReady;
  }
}
