import { ApiRequestError, isIdentityRejection } from '../backend/errors.ts';
import { type Breadcrumb, parseDsn, type ParsedDsn, parseStack, type SentryEvent, serializeEnvelope, type StateSnapshot } from './envelope.ts';
import { scrubString } from './scrub.ts';

const MAX_SENDS_PER_SESSION = 50;
const MAX_BREADCRUMBS = 30;
const NETWORK_FAILURE = /network request failed|failed to fetch|network error|timed out/i;

export interface ReportIdentity {
  sourceId: string | null;
  sessionId: number | null;
  userExternalId: string | null;
}

export interface ReporterOptions {
  dsn: string;
  environment: string;
  release: string;
  sdkVersion: string;
  send: (url: string, body: string) => Promise<unknown>;
  now: () => number;
  randomHex: (length: number) => string;
  appInfo: () => StateSnapshot;
}

function describe(value: unknown): string {
  if (typeof value === 'string') {
    return value;
  }
  try {
    return JSON.stringify(value) ?? String(value);
  } catch {
    return String(value);
  }
}

function toError(context: string, error: unknown): Error {
  if (error instanceof Error) {
    return error;
  }
  return new Error(error === undefined ? context : `${context}: ${describe(error)}`);
}

function fingerprintOf(context: string, error: Error): string[] {
  if (error instanceof ApiRequestError) {
    return ['api-request-error', error.endpoint, String(error.status), error.code ?? ''];
  }
  return [context, error.name];
}

function isNonActionable(error: unknown): error is Error {
  if (error instanceof ApiRequestError) {
    return error.kind !== 'http' || isIdentityRejection(error);
  }
  return error instanceof Error && NETWORK_FAILURE.test(error.message);
}

export class Reporter {
  private readonly target: ParsedDsn | null;

  private readonly breadcrumbs: Breadcrumb[] = [];

  private publishableKey: string | null = null;

  private identityProvider: (() => ReportIdentity) | null = null;

  private sent = 0;

  private reporting = false;

  constructor(private readonly options: ReporterOptions) {
    this.target = parseDsn(options.dsn);
  }

  setPublishableKey(publishableKey: string): void {
    this.publishableKey = publishableKey;
  }

  setIdentityProvider(provider: () => ReportIdentity): void {
    this.identityProvider = provider;
  }

  addBreadcrumb(category: string, message: string): void {
    try {
      this.breadcrumbs.push({ timestamp: this.options.now() / 1000, category, message: scrubString(message), level: 'info' });
      if (this.breadcrumbs.length > MAX_BREADCRUMBS) {
        this.breadcrumbs.shift();
      }
    } catch {
      return;
    }
  }

  report(context: string, error?: unknown): void {
    if (this.reporting) {
      return;
    }
    this.reporting = true;
    try {
      if (isNonActionable(error)) {
        this.addBreadcrumb(error instanceof ApiRequestError ? 'api' : 'network', `${context}: ${error.message}`);
      } else {
        this.capture(context, toError(context, error));
      }
    } catch {
      return;
    } finally {
      this.reporting = false;
    }
  }

  private capture(context: string, error: Error): void {
    if (this.target === null || this.sent >= MAX_SENDS_PER_SESSION) {
      return;
    }
    this.sent += 1;
    const { options } = this;
    const appInfo = options.appInfo();
    const identity = this.readIdentity();
    const sessionId = identity?.sessionId ?? null;
    const event: SentryEvent = {
      event_id: options.randomHex(32),
      timestamp: options.now() / 1000,
      platform: 'javascript',
      level: 'error',
      environment: options.environment,
      release: options.release,
      sdk: { name: 'blar.react-native', version: options.sdkVersion },
      tags: {
        context: scrubString(context),
        sdkVersion: options.sdkVersion,
        publishableKey: this.publishableKey ?? 'unknown',
        sourceId: identity?.sourceId ?? 'unknown',
        sessionId: sessionId !== null ? String(sessionId) : 'none',
        os: String(appInfo.os ?? 'unknown'),
      },
      ...(identity?.userExternalId ? { user: { id: identity.userExternalId } } : {}),
      contexts: { app_info: appInfo },
      fingerprint: fingerprintOf(context, error),
      exception: {
        values: [
          {
            type: error.name,
            value: scrubString(error.message),
            stacktrace: { frames: parseStack(error.stack).map((frame) => ({ ...frame, filename: scrubString(frame.filename) })) },
          },
        ],
      },
      breadcrumbs: { values: [...this.breadcrumbs] },
    };
    this.deliver(this.target, event);
  }

  private readIdentity(): ReportIdentity | null {
    try {
      return this.identityProvider?.() ?? null;
    } catch {
      return null;
    }
  }

  private deliver(target: ParsedDsn, event: SentryEvent): void {
    const body = serializeEnvelope(target.dsn, event, new Date(this.options.now()).toISOString());
    try {
      this.options.send(target.endpoint, body).catch(() => undefined);
    } catch {
      return;
    }
  }
}
