import { Injectable, inject } from '@angular/core';
import { environment } from '../../../environments/environment';
import { TenantResolverService } from './tenant-resolver.service';

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

  getBaseUrl(): string {
    const hostname = this.tenantResolver.getHostname();
    const baseDomain = this.tenantResolver.getBaseDomain();
    const protocol = this.tenantResolver.getProtocol();
    const tenantKey = this.tenantResolver.getTenantKey();
    const tenantMap = (environment as any).tenantApiBaseUrls as Record<string, string> | undefined;
    const localhostUrl = (environment as any).localhostApiUrl as string | undefined;
    const apiTemplate = (environment as any).tenantApiTemplate as string | undefined;

    let url = environment.apiUrl;

    if (this.tenantResolver.isLocalhost() && localhostUrl) {
      url = localhostUrl;
    } else if (tenantMap?.[hostname]) {
      url = tenantMap[hostname];
    } else if (tenantMap?.[tenantKey]) {
      url = tenantMap[tenantKey];
    } else if (apiTemplate && hostname) {
      url = apiTemplate
        .replace('{protocol}', protocol)
        .replace('{baseDomain}', baseDomain)
        .replace('{hostname}', hostname)
        .replace('{tenant}', tenantKey);
    }

    return this.normalizeBaseUrl(url);
  }

  isApiRequest(url: string): boolean {
    if (!url) {
      return false;
    }

    if (url.startsWith('/api')) {
      return true;
    }

    const baseUrl = this.getBaseUrl();
    return url.startsWith(baseUrl);
  }

  toApiUrl(url: string): string {
    if (!url || /^https?:\/\//i.test(url)) {
      return url;
    }

    if (!url.startsWith('/api')) {
      return url;
    }

    const baseUrl = this.getBaseUrl();
    if (baseUrl === '/') {
      return url;
    }

    if (baseUrl === '/api' || baseUrl.endsWith('/api')) {
      return `${baseUrl}${url.slice('/api'.length)}`;
    }

    return `${baseUrl}${url}`;
  }

  private normalizeBaseUrl(url: string): string {
    if (!url || url === '/') {
      return '/';
    }

    return url.replace(/\/+$/, '');
  }
}
