import * as pulumi from '@pulumi/pulumi';
import { serviceLocalEndpoint } from '../utils/local-endpoint';
import { ServiceSecret } from '../utils/secrets';
import { ServiceDeployment } from '../utils/service-deployment';
import { Docker } from './docker';
import { Environment } from './environment';
import { Observability } from './observability';
import { Postgres } from './postgres';
import { Redis } from './redis';
import { Schema } from './schema';
import { Sentry } from './sentry';

export class PostmarkSecret extends ServiceSecret<{
  token: pulumi.Output<string> | string;
  from: string;
  messageStream: string;
}> {}

export function deployWorkflows({
  environment,
  heartbeat,
  image,
  docker,
  sentry,
  postgres,
  observability,
  postmarkSecret,
  schema,
  redis,
}: {
  postgres: Postgres;
  observability: Observability;
  environment: Environment;
  image: string;
  docker: Docker;
  heartbeat?: string;
  sentry: Sentry;
  postmarkSecret: PostmarkSecret;
  schema: Schema;
  redis: Redis;
}) {
  return (
    new ServiceDeployment(
      'workflow-service',
      {
        imagePullSecret: docker.secret,
        env: {
          ...environment.envVars,
          SENTRY: sentry.enabled ? '1' : '0',
          EMAIL_PROVIDER: 'postmark',
          HEARTBEAT_ENDPOINT: heartbeat ?? '',
          OPENTELEMETRY_COLLECTOR_ENDPOINT:
            observability.enabled && observability.tracingEndpoint
              ? observability.tracingEndpoint
              : '',
          LOG_JSON: '1',
          SCHEMA_ENDPOINT: serviceLocalEndpoint(schema.service),
        },
        readinessProbe: '/_readiness',
        livenessProbe: '/_health',
        startupProbe: '/_health',
        exposesMetrics: true,
        image,
        replicas: environment.podsConfig.general.replicas,
      },
      [redis.deployment, redis.service],
    )
      // PG
      .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('EMAIL_FROM', postmarkSecret, 'from')
      .withSecret('EMAIL_PROVIDER_POSTMARK_TOKEN', postmarkSecret, 'token')
      .withSecret('EMAIL_PROVIDER_POSTMARK_MESSAGE_STREAM', postmarkSecret, 'messageStream')
      .withConditionalSecret(sentry.enabled, 'SENTRY_DSN', sentry.secret, 'dsn')
      // Redis
      .withSecret('REDIS_HOST', redis.secret, 'host')
      .withSecret('REDIS_PORT', redis.secret, 'port')
      .withSecret('REDIS_PASSWORD', redis.secret, 'password')
      .deploy()
  );
}
