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;
  contactPhone: string;
  companyAddress: string;
  themeId: string;
}

@Injectable({ providedIn: 'root' })
export class UiRuntimeFacade {
  private readonly state = signal<UiRuntimeState>({
    marketplaceName: '',
    marketplaceDisplayName: '',
    logoUrl: '',
    contactEmail: '',
    contactPhone: '',
    companyAddress: '',
    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 ?? '',
      contactPhone: bootstrap.branding.supportPhone ?? bootstrap.company?.contacts?.phone ?? '',
      companyAddress: bootstrap.company?.address?.street ?? '',
      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;
  }

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

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

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