// Export guardrails: row cap (warn + cancel) and per-request timeout (fail).
export const MAX_EXPORT_ROWS = 10000;
export const EXPORT_REQUEST_TIMEOUT_MS = 50000;

export class ExportLimitError extends Error {
  readonly count: number;
  readonly limit: number;
  constructor(count: number, limit = MAX_EXPORT_ROWS) {
    super(
      `This export has ${count.toLocaleString()} rows, which exceeds the ${limit.toLocaleString()}-row limit.`,
    );
    this.name = "ExportLimitError";
    this.count = count;
    this.limit = limit;
  }
}

export class ExportTimeoutError extends Error {
  readonly ms: number;
  constructor(ms = EXPORT_REQUEST_TIMEOUT_MS) {
    super(`A request took longer than ${ms} ms and the export timed out.`);
    this.name = "ExportTimeoutError";
    this.ms = ms;
  }
}

export function withTimeout<T>(
  promise: Promise<T>,
  ms = EXPORT_REQUEST_TIMEOUT_MS,
): Promise<T> {
  return new Promise<T>((resolve, reject) => {
    const id = setTimeout(() => reject(new ExportTimeoutError(ms)), ms);
    promise.then(
      (value) => {
        clearTimeout(id);
        resolve(value);
      },
      (err) => {
        clearTimeout(id);
        reject(err);
      },
    );
  });
}
