import { Inject, Injectable, Logger } from '@nestjs/common';
import { GetParameterCommand, SSMClient } from '@aws-sdk/client-ssm';
import { SecretStoreService } from './secret-store.service';
import { Config } from '../config/config.interface';
import { CONFIG_PROVIDER_NAME } from '../appwrite.constants';

@Injectable()
export class ParameterStoreService extends SecretStoreService {
  private readonly logger = new Logger(ParameterStoreService.name);
  private client: SSMClient;

  constructor(@Inject(CONFIG_PROVIDER_NAME) private readonly config: Config) {
    super();
  }

  public async getSecretString(secretName: string): Promise<string | undefined> {
    try {
      const serviceAccount = await this.getSsmClient().send(new GetParameterCommand({
        Name: secretName,
        WithDecryption: true
      }));
      return serviceAccount.Parameter?.Value;
    } catch (err) {
      this.logger.error(err);
      return undefined;
    }
  }

  private getSsmClient(): SSMClient {
    if (this.client) {
      return this.client;
    }
    this.client = new SSMClient({
      region: this.config.AWS_REGION,
    });
    return this.client;
  }
}
