/**
 * React Native analytics tracker: small in-memory queue + periodic flush.
 * No PII is stored locally beyond anonymous/session ids.
 */
import type { AnalyticsBatchResult, AnalyticsEvent, TrackerConfig } from "./types.js";

export type SendBatch = (events: AnalyticsEvent[]) => Promise<AnalyticsBatchResult>;

export interface Tracker {
  track: (event: AnalyticsEvent) => void;
  flush: () => Promise<AnalyticsBatchResult>;
  setSessionId: (sessionId: string) => void;
  setAuthToken: (token: string | undefined) => void;
  setAnonymousId: (anonymousId: string) => void;
  destroy: () => void;
}

/**
 * Create a tracker that batches events in memory and flushes periodically.
 * In a React Native app the storage adapter (AsyncStorage) should persist
 * anonymousId; this tracker intentionally keeps no durable local state.
 */
export function createTracker(config: TrackerConfig, send: SendBatch): Tracker {
  const maxBatchSize = config.maxBatchSize ?? 20;
  const flushIntervalMs = config.flushIntervalMs ?? 10_000;
  let queue: AnalyticsEvent[] = [];
  let sessionId = config.sessionId ?? "";
  let authToken = config.authToken ?? "";
  let anonymousId = config.anonymousId ?? "";

  function enrich(event: AnalyticsEvent): AnalyticsEvent {
    return {
      ...event,
      anonymousId: event.anonymousId ?? anonymousId,
      sessionId: event.sessionId ?? sessionId,
      appVersion: event.appVersion ?? config.appVersion,
      platform: event.platform ?? config.platform,
      locale: event.locale ?? config.locale,
      occurredAt: event.occurredAt ?? new Date().toISOString(),
    };
  }

  async function flush(): Promise<AnalyticsBatchResult> {
    if (queue.length === 0) return { accepted: 0 };
    const batch = queue.slice(0, maxBatchSize);
    queue = queue.slice(maxBatchSize);
    try {
      const result = await send(batch);
      if (result.rejected && result.rejected > 0) {
        // Put rejected events back at the front of the queue only if the
        // server asked us to retry (e.g. rate limit). For validation errors
        // we drop them to avoid an infinite retry loop.
        const retryable = batch.filter((_, i) =>
          result.errors?.some((e) => e.index === i && e.message.toLowerCase().includes("rate limit")),
        );
        queue = [...retryable, ...queue];
      }
      return result;
    } catch (err) {
      // Network failure: keep events for next flush.
      queue = [...batch, ...queue];
      return { accepted: 0, rejected: batch.length, errors: [{ index: 0, message: String(err) }] };
    }
  }

  const timer = flushIntervalMs > 0 ? setInterval(() => void flush(), flushIntervalMs) : null;

  return {
    track(event: AnalyticsEvent) {
      queue.push(enrich(event));
      if (queue.length >= maxBatchSize) {
        void flush();
      }
    },
    flush,
    setSessionId(next) {
      sessionId = next;
    },
    setAuthToken(next) {
      authToken = next ?? "";
    },
    setAnonymousId(next) {
      anonymousId = next;
    },
    destroy() {
      if (timer) clearInterval(timer);
    },
  };
}

/**
 * Default HTTP sender for the batch endpoint.
 * This function has no React Native dependencies and can be used anywhere.
 */
export function createHttpSend(config: { apiBaseUrl: string; authToken?: string }): SendBatch {
  return async (events) => {
    const res = await fetch(`${config.apiBaseUrl.replace(/\/$/, "")}/v1/analytics/events`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        ...(config.authToken ? { Authorization: `Bearer ${config.authToken}` } : {}),
      },
      body: JSON.stringify({ events }),
    });
    if (!res.ok) {
      const text = await res.text().catch(() => "unknown error");
      throw new Error(`Analytics API ${res.status}: ${text}`);
    }
    return (await res.json().catch(() => ({ accepted: events.length }))) as AnalyticsBatchResult;
  };
}
