import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { ConfigService } from './config.service';
import { CONFIG_PROVIDER } from './config-provider.token';
import { ConfigProvider } from './config-provider.interface';
import { BootstrapConfig, DEFAULT_BOOTSTRAP } from '../../shared/models/config';

function makeRealBootstrap(overrides: Partial<BootstrapConfig> = {}): BootstrapConfig {
  return { ...DEFAULT_BOOTSTRAP, published: true, tenant: { ...DEFAULT_BOOTSTRAP.tenant, name: 'Acme' }, ...overrides };
}

describe('ConfigService', () => {
  let provider: jasmine.SpyObj<ConfigProvider>;

  function setup(response: BootstrapConfig): ConfigService {
    provider = jasmine.createSpyObj<ConfigProvider>('ConfigProvider', ['loadBootstrap']);
    provider.loadBootstrap.and.returnValue(of(response));
    TestBed.configureTestingModule({
      providers: [ConfigService, { provide: CONFIG_PROVIDER, useValue: provider }],
    });
    return TestBed.inject(ConfigService);
  }

  it('caches the real response when published is true', done => {
    const real = makeRealBootstrap();
    const service = setup(real);

    service.loadBootstrap().subscribe(result => {
      expect(result.tenant.name).toBe('Acme');
      expect(service.getBootstrapSnapshot()).toEqual(real);
      done();
    });
  });

  it('swaps to DEFAULT_BOOTSTRAP when published is false', done => {
    const draft = makeRealBootstrap({ published: false });
    const service = setup(draft);

    service.loadBootstrap().subscribe(result => {
      expect(result).toEqual(DEFAULT_BOOTSTRAP);
      expect(service.getBootstrapSnapshot()).toEqual(DEFAULT_BOOTSTRAP);
      done();
    });
  });

  it('treats a missing published field as published (backward compatible)', done => {
    const legacy = makeRealBootstrap();
    delete (legacy as Partial<BootstrapConfig>).published;
    const service = setup(legacy);

    service.loadBootstrap().subscribe(result => {
      expect(result.tenant.name).toBe('Acme');
      expect(result).not.toEqual(DEFAULT_BOOTSTRAP);
      done();
    });
  });
});
