import { DOCUMENT } from '@angular/common';
import { Injectable, inject } from '@angular/core';
import { environment } from '../../../environments/environment';

@Injectable({ providedIn: 'root' })
export class TenantResolverService {
  private readonly document = inject(DOCUMENT);

  getHostname(): string {
    const host = this.document?.location?.hostname ?? '';
    return host.toLowerCase();
  }

  getProtocol(): string {
    return this.document?.location?.protocol ?? 'https:';
  }

  getBaseDomain(): string {
    const segments = this.getHostname().split('.').filter(Boolean);
    if (segments.length <= 2) {
      return segments.join('.');
    }

    const topLevelDomain = segments.at(-1) ?? '';
    const secondLevelDomain = segments.at(-2) ?? '';
    const usesCountryCodeSecondLevel =
      topLevelDomain.length === 2 && secondLevelDomain.length <= 3;

    return segments.slice(usesCountryCodeSecondLevel ? -3 : -2).join('.');
  }

  isLocalhost(): boolean {
    const hostname = this.getHostname();
    return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1';
  }

  getTenantKey(): string {
    if (this.isLocalhost()) {
      return (environment as any).fallbackTenantKey ?? 'default';
    }

    const hostname = this.getHostname();
    const segments = hostname.split('.').filter(Boolean);
    if (segments.length === 0) {
      return (environment as any).fallbackTenantKey ?? 'default';
    }

    if (segments[0] === 'www' && segments.length > 1) {
      return segments[1];
    }

    return segments[0];
  }
}
