import { Injectable, effect, signal } from '@angular/core';
import { ConfigService } from '../../core/config/config.service';
import { BootstrapConfig } from '../../shared/models/config';

interface UiRuntimeState {
  marketplaceName: string;
  marketplaceDisplayName: string;
  logoUrl: string;
  contactEmail: string;
  themeId: string;
}

@Injectable({ providedIn: 'root' })
export class UiRuntimeFacade {
  private readonly state = signal<UiRuntimeState>({
    marketplaceName: '',
    marketplaceDisplayName: '',
    logoUrl: '',
    contactEmail: '',
    themeId: ''
  });

  constructor(private readonly configService: ConfigService) {
    effect(() => {
      this.configService.bootstrapRevision();
      const bootstrap = this.configService.getBootstrapSnapshot();
      if (bootstrap) {
        this.reloadFromBootstrap(bootstrap);
      }
    });

    this.configService.loadBootstrap().subscribe();
  }

  reloadFromBootstrap(bootstrap: BootstrapConfig): void {
    this.state.set({
      marketplaceName: bootstrap.branding.brandName,
      marketplaceDisplayName: bootstrap.branding.brandName,
      logoUrl: bootstrap.branding.logoUrl,
      contactEmail: bootstrap.branding.supportEmail ?? bootstrap.company?.contacts?.email ?? '',
      themeId: bootstrap.theme.themeId
    });
  }

  marketplaceName(): string {
    return this.state().marketplaceName;
  }

  marketplaceDisplayName(): string {
    return this.state().marketplaceDisplayName;
  }

  logoUrl(): string {
    return this.state().logoUrl;
  }

  contactEmail(): string {
    return this.state().contactEmail;
  }

  themeId(): string {
    return this.state().themeId;
  }
}