import { TestBed } from '@angular/core/testing';
import { ApiConfigService } from './api-config.service';
import { TenantResolverService } from './tenant-resolver.service';

describe('ApiConfigService', () => {
  let service: ApiConfigService;
  let tenantResolver: jasmine.SpyObj<TenantResolverService>;

  beforeEach(() => {
    tenantResolver = jasmine.createSpyObj<TenantResolverService>(
      'TenantResolverService',
      ['getHostname', 'getBaseDomain', 'getProtocol', 'getTenantKey', 'isLocalhost']
    );
    tenantResolver.getBaseDomain.and.returnValue('gorbushka.market');
    tenantResolver.getTenantKey.and.returnValue('gorbushka');
    tenantResolver.getProtocol.and.returnValue('https:');
    tenantResolver.isLocalhost.and.returnValue(false);

    TestBed.configureTestingModule({
      providers: [
        ApiConfigService,
        { provide: TenantResolverService, useValue: tenantResolver }
      ]
    });

    service = TestBed.inject(ApiConfigService);
  });

  it('uses the current customer hostname for the production API base URL', () => {
    tenantResolver.getHostname.and.returnValue('gorbushka.market');

    expect(service.getBaseUrl()).toBe('https://api.gorbushka.market');
  });

  it('uses the shared base-domain API for a tenant subdomain', () => {
    tenantResolver.getHostname.and.returnValue('store1.example.com');
    tenantResolver.getBaseDomain.and.returnValue('example.com');

    expect(service.getBaseUrl()).toBe('https://api.example.com');
  });

  it('uses the shared base-domain API for www', () => {
    tenantResolver.getHostname.and.returnValue('www.gorbushka.market');

    expect(service.getBaseUrl()).toBe('https://api.gorbushka.market');
  });

  it('preserves the API namespace when targeting a tenant backend', () => {
    tenantResolver.getHostname.and.returnValue('gorbushka.market');

    expect(service.toApiUrl('/api/v2/storefront/cart'))
      .toBe('https://api.gorbushka.market/api/v2/storefront/cart');
  });

  it('does not duplicate the API prefix for localhost proxy requests', () => {
    tenantResolver.getHostname.and.returnValue('localhost');
    tenantResolver.getTenantKey.and.returnValue('default');
    tenantResolver.isLocalhost.and.returnValue(true);

    expect(service.toApiUrl('/api/v2/storefront/cart')).toBe('/api/v2/storefront/cart');
  });

  it('leaves absolute and non-API URLs unchanged', () => {
    tenantResolver.getHostname.and.returnValue('gorbushka.market');

    expect(service.toApiUrl('https://cdn.example.com/image.png'))
      .toBe('https://cdn.example.com/image.png');
    expect(service.toApiUrl('/assets/config.json')).toBe('/assets/config.json');
  });
});
