import { ServiceDeployment } from '../utils/service-deployment';
import { DbMigrations } from './db-migrations';
import { Docker } from './docker';
import { Environment } from './environment';
import { Observability } from './observability';
import { Postgres } from './postgres';
import { Redis } from './redis';
import { Sentry } from './sentry';

export type Tokens = ReturnType<typeof deployTokens>;

export function deployTokens({
  environment,
  dbMigrations,
  heartbeat,
  image,
  docker,
  postgres,
  redis,
  sentry,
  observability,
}: {
  observability: Observability;
  image: string;
  environment: Environment;
  dbMigrations: DbMigrations;
  heartbeat?: string;
  docker: Docker;
  redis: Redis;
  postgres: Postgres;
  sentry: Sentry;
}) {
  return new ServiceDeployment(
    'tokens-service',
    {
      imagePullSecret: docker.secret,
      readinessProbe: '/_readiness',
      livenessProbe: '/_health',
      startupProbe: '/_health',
      exposesMetrics: true,
      availabilityOnEveryNode: true,
      replicas: environment.podsConfig.general.replicas,
      image,
      env: {
        ...environment.envVars,
        SENTRY: sentry.enabled ? '1' : '0',
        HEARTBEAT_ENDPOINT: heartbeat ?? '',
        OPENTELEMETRY_TRACE_USAGE_REQUESTS: observability.enabledForUsageService ? '1' : '',
        OPENTELEMETRY_COLLECTOR_ENDPOINT:
          observability.enabled && observability.tracingEndpoint
            ? observability.tracingEndpoint
            : '',
      },
    },
    [dbMigrations],
  )
    .withSecret('POSTGRES_HOST', postgres.pgBouncerSecret, 'host')
    .withSecret('POSTGRES_PORT', postgres.pgBouncerSecret, 'port')
    .withSecret('POSTGRES_USER', postgres.pgBouncerSecret, 'user')
    .withSecret('POSTGRES_PASSWORD', postgres.pgBouncerSecret, 'password')
    .withSecret('POSTGRES_DB', postgres.pgBouncerSecret, 'database')
    .withSecret('POSTGRES_SSL', postgres.pgBouncerSecret, 'ssl')
    .withSecret('REDIS_HOST', redis.secret, 'host')
    .withSecret('REDIS_PORT', redis.secret, 'port')
    .withSecret('REDIS_PASSWORD', redis.secret, 'password')
    .withConditionalSecret(sentry.enabled, 'SENTRY_DSN', sentry.secret, 'dsn')
    .deploy();
}
