import { Injectable, inject } from '@angular/core';
import { take } from 'rxjs/operators';
import { AnalyticsEventType } from '../models/analytics-event.model';
import { ANALYTICS_GATEWAY } from './analytics-gateway.token';
import { environment } from '../../../../environments/environment';

/**
 * Thin call-site wrapper so storefront components fire events without
 * knowing about the gateway/token plumbing. isSynthetic is derived from the
 * build environment, never client-settable at the call site (per
 * docs/backend/TRACK-A-ANALYTICS-CONTRACT.md §6 - synthetic traffic must be
 * inseparable-by-accident from production data).
 */
@Injectable({ providedIn: 'root' })
export class AnalyticsService {
  private readonly gateway = inject(ANALYTICS_GATEWAY);

  track(eventType: AnalyticsEventType, properties: Record<string, unknown> = {}): void {
    this.gateway.track({
      eventType,
      properties,
      isSynthetic: !environment.production,
    }).pipe(take(1)).subscribe();
  }
}
