import { Injectable, inject, signal } from '@angular/core';
import { take } from 'rxjs/operators';
import { LifecycleAdvanceResult, Marketplace, MarketplaceDomain } from '../../../../core/marketplace-registry/models/marketplace.model';
import { MARKETPLACE_GATEWAY } from '../../../../core/marketplace-registry/services/marketplace-gateway.token';

@Injectable({ providedIn: 'root' })
export class AdminMarketplacesFacade {
  private readonly gateway = inject(MARKETPLACE_GATEWAY);

  readonly marketplaces = signal<Marketplace[]>([]);
  readonly domains = signal<MarketplaceDomain[]>([]);
  readonly lifecycle = signal<LifecycleAdvanceResult | null>(null);
  readonly loading = signal(false);

  load(): void {
    this.loading.set(true);
    this.gateway.loadMarketplaces().pipe(take(1)).subscribe(items => {
      this.marketplaces.set(items);
      this.loading.set(false);
      const first = items[0];
      if (first) {
        this.gateway.loadDomains(first.id).pipe(take(1)).subscribe(d => this.domains.set(d));
        this.gateway.loadLifecycle(first.id).pipe(take(1)).subscribe(l => this.lifecycle.set(l));
      }
    });
  }
}
