@Injectable()
export class AwsService {
  public async isMainInstance(): Promise<boolean> {
    /*
     * インスタンスメタデータを取得するための手続き。IMDSv2で実装。
     * https://docs.aws.amazon.com/ja_jp/AWSEC2/latest/UserGuide/instancedata-data-retrieval.html
     */
    const token = await firstValueFrom(
      this.http
        .put(
          'http://169.254.169.254/latest/api/token',
          {},
          {
            headers: {
              'X-aws-ec2-metadata-token-ttl-seconds': '21600',
            },
          },
        )
        .pipe(map((d) => d.data)),
    ).catch((e) => console.log(e));

    if (token === undefined) {
      console.error('AWS EC2以外での実行のため結果を得ることができません');
      return false;
    }

    // 実行中のInstanceIdを取得
    const instanceId = await firstValueFrom(
      this.http
        .get('http://169.254.169.254/latest/meta-data/instance-id', {
          headers: {
            'X-aws-ec2-metadata-token': token,
          },
        })
        .pipe(map((d) => d.data)),
    );

    const input = {
      EnvironmentName: 'tipsys-api-v8', // 自分のプロジェクトのEnvironmentNameで
    };
    const command = new DescribeEnvironmentResourcesCommand(input);
    const response = await this.ebClient.send(command);
    if (response.$metadata.httpStatusCode !== 200) {
      throw new Error('ebClientのhttpStatusCodeが' + response.$metadata.httpStatusCode);
    }
    return response.EnvironmentResources.Instances[0].Id === instanceId;
  }
}