import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';

export type RuntimeProviderMode = 'mock' | 'api' | 'remote-config';

@Injectable({ providedIn: 'root' })
export class RuntimeProviderStrategyService {
  private isLocalhost(): boolean {
    if (typeof window === 'undefined') {
      return false;
    }

    const host = window.location.hostname.toLowerCase();
    return host === 'localhost' || host === '127.0.0.1' || host === '::1';
  }

  getBootstrapProviderMode(): RuntimeProviderMode {
    if (environment.useMockData) {
      return 'mock';
    }

    // Local dev must use mocked bootstrap while API data can stay production-based.
    if ((environment as any).useMockBootstrapOnLocal === true && this.isLocalhost()) {
      return 'mock';
    }

    return 'api';
  }

  getBackofficeProviderMode(): RuntimeProviderMode {
    if (environment.useMockData) {
      return 'mock';
    }

    return 'api';
  }

  getProductProviderMode(): RuntimeProviderMode {
    if (environment.useMockData) {
      return 'mock';
    }

    return 'api';
  }

  getCategoryProviderMode(): RuntimeProviderMode {
    if (environment.useMockData) {
      return 'mock';
    }

    // Same rationale as getBootstrapProviderMode(): the admin Categories CRUD
    // gateway has a real local-mock implementation (AdminCategoriesLocalGateway)
    // built specifically so create/edit/delete/reorder can be exercised without
    // a backend. Local dev has no reachable backoffice API, so fall back to it
    // there while production keeps hitting the real API unconditionally.
    if ((environment as any).useMockBootstrapOnLocal === true && this.isLocalhost()) {
      return 'mock';
    }

    return 'api';
  }
}
