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

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

  getBaseUrl(): string {
    const tenantKey = this.tenantResolver.getTenantKey();
    const bootstrapUrl = this.resolveBootstrapApiBaseUrl();
    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?.[tenantKey]) {
      url = tenantMap[tenantKey];
    } else if (apiTemplate) {
      url = apiTemplate.replace('{tenant}', tenantKey);
    } else if (bootstrapUrl) {
      // Bootstrap API override is opt-in and only for absolute URLs.
      url = bootstrapUrl;
    }

    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();
    const path = url.slice('/api'.length);
    return `${baseUrl}${path.startsWith('/') ? path : `/${path}`}`;
  }

  private resolveBootstrapApiBaseUrl(): string | null {
    const allowBootstrapApiOverride = (environment as any).allowBootstrapApiOverride === true;
    if (!allowBootstrapApiOverride) {
      return null;
    }

    const bootstrap = this.configService.getBootstrapSnapshot() as any;
    if (!bootstrap) {
      return null;
    }

    const endpointBase = bootstrap?.apiEndpoints?.website?.baseUrl;
    if (typeof endpointBase === 'string' && this.isAbsoluteHttpUrl(endpointBase)) {
      return endpointBase;
    }

    const tenantBase = bootstrap?.tenant?.apiBaseUrl;
    if (typeof tenantBase === 'string' && this.isAbsoluteHttpUrl(tenantBase)) {
      return tenantBase;
    }

    return null;
  }

  private isAbsoluteHttpUrl(url: string): boolean {
    return /^https?:\/\//i.test(url.trim());
  }

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

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