terraform {
  backend "s3" {}
}

provider aws {
  shared_credentials_file = var.shared_credentials_file
  profile                 = var.profile
  region                  = var.region
  skip_metadata_api_check = var.skip_metadata_api_check
}

locals {
  source_file = "${path.module}/../bin/main"
  output_path = "${path.module}/../bin/spotify_partneremails_ingest.zip"
  name_prefix = lower("${var.env_prefix}-${var.platform_name}")
}

data aws_iam_role this {
  name = var.lambda_role_name
}

data archive_file this {
  type = "zip"
  source_file = local.source_file
  output_path = local.output_path
}

resource aws_lambda_function this {
  filename         = data.archive_file.this.output_path
  function_name    = "${local.name_prefix}-spotify_partneremails_ingest"
  role             = data.aws_iam_role.this.arn
  handler          = "main"
  source_code_hash = data.archive_file.this.output_base64sha256
  runtime          = "go1.x"
  memory_size      = 2048
  timeout          = 900

  environment {
    variables = {
      DAYS_TO_CHECK                 = 7
      S3_BUCKET                     = var.lambda_s3_bucket_name
      S3_REGION                     = var.lambda_s3_region
      S3_PREFIX                     = var.lambda_s3_prefix
      SPOTIFY_CREDENTIALS_SECRET_ID = var.lambda_spotify_credentials_secret_id
    }
  }
}

resource aws_cloudwatch_event_rule this {
  schedule_expression = "rate(3 hours)"
}

resource aws_cloudwatch_event_target this {
  rule = aws_cloudwatch_event_rule.this.name
  arn  = aws_lambda_function.this.arn
}

resource aws_lambda_permission this {
  statement_id  = "AllowExecutionFromCloudWatch"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.this.function_name
  principal     = "events.amazonaws.com"
  source_arn    = aws_cloudwatch_event_rule.this.arn
}
