import { injectable, unmanaged } from 'inversify';
import { AnalyticsApiClient } from '@/lib/api/analytics/AnalyticsApiClient';
import { RecordPageViewOutputViewModel } from '@/lib/view-models/RecordPageViewOutputViewModel';
import { RecordEngagementOutputViewModel } from '@/lib/view-models/RecordEngagementOutputViewModel';
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
import { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporter';
import { Service } from '@/lib/contracts/services/Service';

@injectable()
export class AnalyticsService implements Service {
  private readonly apiClient: AnalyticsApiClient;

  constructor(@unmanaged() apiClient?: AnalyticsApiClient) {
    if (apiClient) {
      this.apiClient = apiClient;
    } else {
      const baseUrl = getWebsiteApiBaseUrl();
      const logger = new ConsoleLogger();
      const errorReporter = new EnhancedErrorReporter(logger);
      this.apiClient = new AnalyticsApiClient(baseUrl, errorReporter, logger);
    }
  }

  async recordPageView(input: { path: string; userId?: string }): Promise<RecordPageViewOutputViewModel> {
    const data = await this.apiClient.recordPageView({
      entityType: 'page',
      entityId: input.path,
      visitorType: input.userId ? 'user' : 'guest',
      sessionId: 'temp-session', // Should come from a session service
      ...input
    });
    return new RecordPageViewOutputViewModel(data);
  }

  async recordEngagement(input: { eventType: string; userId?: string; metadata?: Record<string, any> }): Promise<RecordEngagementOutputViewModel> {
    const data = await this.apiClient.recordEngagement({
      action: input.eventType,
      entityType: 'ui_element',
      entityId: 'unknown',
      actorType: input.userId ? 'user' : 'guest',
      sessionId: 'temp-session', // Should come from a session service
      ...input
    });
    return new RecordEngagementOutputViewModel(data);
  }
}
