import * as core from '@actions/core'
import { STSClient, AssumeRoleWithWebIdentityCommand } from '@aws-sdk/client-sts'
import { PlatformConfig } from 'types'
import { logInfo, logError } from 'log'

export class AwsCredentialsClient {

  static resolveAwsCredentials({ awsAccountId, awsRegion, awsRoleToAssume }: PlatformConfig) {
    // If awsRoleToAssume is present, then we assume we run in a github workflow
    // If awsRoleToAssume is not present, then we assume they are resolved localy by aws-sdk
    if (!awsRoleToAssume) {
      logInfo({ message: `[AwsCredentialsClient] No aws role to assume was found, leaving auth logic to @aws-sdk package` })
      return Promise.resolve(undefined)
    }

    const stsClient = new STSClient({ region: awsRegion })

    logInfo({ message: '[AwsCredentialsClient] Fetching GitHub ID token' })
    return core.getIDToken('sts.amazonaws.com')
      .then(webIdentityToken => {
        logInfo({ message: `[AwsCredentialsClient] Attempting to resolve aws credentials by assuming the role: ${awsRoleToAssume}` })
        return stsClient.send(new AssumeRoleWithWebIdentityCommand({
          RoleArn: `arn:aws:iam::${awsAccountId}:role/${awsRoleToAssume}`,
          RoleSessionName: 'GitHubActions',
          DurationSeconds: 15 * 60,
          WebIdentityToken: webIdentityToken
        }))
      })
      .then(responseData => ({
        // Don't ask
        AccessKeyId: responseData.Credentials.AccessKeyId,
        SessionToken: responseData.Credentials.SessionToken,
        SecretAccessKey: responseData.Credentials.SecretAccessKey,
        accessKeyId: responseData.Credentials.AccessKeyId,
        sessionToken: responseData.Credentials.SessionToken,
        secretAccessKey: responseData.Credentials.SecretAccessKey,
      }))
      .catch(error => {
        logError({ message: '[AwsCredentialsClient] Could not resolve temporary credentials', error })
        return undefined
      })
  }

}
