import { Injectable, inject } from '@angular/core';
import { Observable, map, of } from 'rxjs';
import { LifecycleAdvanceResult, Marketplace, MarketplaceDomain } from '../models/marketplace.model';
import { MarketplaceGateway } from './marketplace-gateway.interface';
import { ConfigService } from '../../config/config.service';

/**
 * The platform runs one live tenant per deployment today - there is no
 * registry of multiple marketplaces anywhere in the codebase. This derives
 * a single-row "registry" from the current tenant's own bootstrap so the
 * shape is real, ready to become a genuine multi-row registry once
 * docs/backend/PHASE-9-TENANT-REGISTRY-DOMAINS-CONTRACT.md ships.
 */
@Injectable({ providedIn: 'root' })
export class MarketplaceLocalGateway implements MarketplaceGateway {
  private readonly configService = inject(ConfigService);

  loadMarketplaces(): Observable<Marketplace[]> {
    const bootstrap = this.configService.getBootstrapSnapshot();
    return of([{
      id: 'current',
      name: bootstrap?.branding?.brandName || 'This marketplace',
      code: 'current',
      type: 'commerce',
      ownerId: 'unknown',
      countries: [],
      currencies: [],
      lifecycleState: 'live',
    }]);
  }

  loadDomains(marketplaceId: string): Observable<MarketplaceDomain[]> {
    if (typeof window === 'undefined') {
      return of([]);
    }
    return of([{ marketplaceId, domain: window.location.hostname, type: 'production', status: 'active' }]);
  }

  loadLifecycle(_marketplaceId: string): Observable<LifecycleAdvanceResult> {
    return of({ currentState: 'live', nextState: null, blockers: [] });
  }
}
