import express from 'express';
import * as Sentry from '@sentry/node';

interface ISentryServiceConfig {
  dsn: string;
  isProduction: boolean;
}

export class SentryService {
  private readonly config: ISentryServiceConfig;

  constructor(
    config: ISentryServiceConfig,
  ) {
    this.config = config;
    if (this.config.isProduction) {
      Sentry.init({
        dsn: this.config.dsn,
        tracesSampleRate: 1.0,
      });
    }
  }

  catchErrorBySentry(res: express.Response, err?: Error, status = 500, data?: object) {
    console.error(err);
    if (this.config.isProduction) {
      Sentry.captureException(err);
      if (res) {
        return res.status(status).json({ message: err?.message ?? 'Something went wrong', ...data });
      }
    }
  }
}
