import { AppConfigDataClientConfig } from '@aws-sdk/client-appconfigdata'
import { S3ClientConfig } from '@aws-sdk/client-s3'
import { SESv2ClientConfig } from '@aws-sdk/client-sesv2'
import { Stage } from './misc'
import { StageId } from '@core/types'

const region = process.env.AWS_REGION ?? process.env.AWS_DEFAULT_REGION
const accessKeyId = process.env.AWS_ACCESS_KEY
const secretAccessKey = process.env.AWS_SECRET_KEY
const appConfigPollInterval = Number.parseInt(process.env.APP_CONFIG_POLL_INTERVAL || '60_000')

if (!region) {
	throw new Error('Please provide AWS_REGION')
}

// Use explicit static credentials only when both are provided; otherwise fall back to the
// default AWS credential provider chain (e.g. an ECS task role) so the service can run with a
// task role instead of long-lived static keys. If static keys are set, behaviour is unchanged.
const credentials = accessKeyId && secretAccessKey ? { accessKeyId, secretAccessKey } : undefined

export const AWS_OPTIONS = { region, ...(credentials ? { credentials } : {}) }

export const S3Config: S3ClientConfig = AWS_OPTIONS
export const SESConfig: SESv2ClientConfig = AWS_OPTIONS
export const AppConfigConfig: AppConfigDataClientConfig = AWS_OPTIONS

export const APPCONFIG_CONFIG = {
	APPLICATION: process.env.APPCONFIG_APPLICATION || 'backend',
	ENVIRONMENT: Stage === StageId.LOCAL ? 'staging' : Stage,
	CONFIGURATION: `backend-${Stage === StageId.LOCAL ? 'staging' : Stage}`,
	POLL_INTERVAL: appConfigPollInterval,
}
