provider "aws" {
  region = var.aws_region
}

terraform {
  backend "s3" {
    bucket  = "dev-orcd-terraform-state"
    key     = "dev/lambda-podcast/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

module "lambda_podcast_notifications_sentry" {
  source              = "git@github.com:theorchard/terraform-sentry.git//?ref=2.0.1"
  service_name        = var.lambda_name
  environment         = var.environment
  application_family  = var.application_family
  team                = var.environment
  platform            = "python"
}

module "lambda_podcast_notifications_owsrequest" {
  source = "git@github.com:theorchard/terraform-owsrequest.git//?ref=1.0.0"

  environment_name = var.environment
  service_name     = var.lambda_name
}

module "lambda_podcast_notification" {
  source                   = "git@github.com:theorchard/terraform-lambda.git//?ref=1.3.3"
  lambda_name              = var.lambda_name
  lambda_description       = "Lambda scheduled hourly to trigger email notifications for host read ads and scheduled episodes."
  use_custom_function_name = true
  custom_function_name     = "${var.lambda_name}-${var.environment}"
  environment              = var.environment
  application_family       = var.application_family
  datadog_enabled = false

  lambda_function_environment_variables = {
    ENVIRONMENT = var.environment
  }

  iam_managed_policy_attachments = [
    module.lambda_podcast_notifications_owsrequest.policy_arn_output
  ]
}

resource "aws_cloudwatch_event_rule" "host_read_ads_event" {
  name                = "${var.environment}-podcast-host-read-ads-notifications"
  description         = "Event for sending reminder emails about Host Read Ads that are 1 day away from their due date"
  schedule_expression = "rate(1 hour)"
}

resource "aws_cloudwatch_event_target" "host_read_ads_event_target" {
  rule      = aws_cloudwatch_event_rule.host_read_ads_event.name
  target_id = "${var.environment}-podcast-host-read-ads-notifications"
  arn       = module.lambda_podcast_notification.lambda_arn
  input     = "{\"eventType\": \"ad-due-tomorrow\"}"
}

resource "aws_lambda_permission" "allow_cloudwatch_host_read_ads_event" {
  statement_id  = "AllowHostReadAdsExecutionFromCloudWatch"
  action        = "lambda:InvokeFunction"
  function_name = module.lambda_podcast_notification.lambda_name
  principal     = "events.amazonaws.com"
  source_arn    = aws_cloudwatch_event_rule.host_read_ads_event.arn
}


resource "aws_cloudwatch_event_rule" "host_read_ads_event_past_due" {
  name                = "${var.environment}-podcast-host-read-ads-past-due-notifications"
  description         = "Event for sending reminder emails about Host Read Ads that are past due"
  schedule_expression = "rate(1 hour)"
}

resource "aws_cloudwatch_event_target" "host_read_ads_event_past_due_target" {
  rule      = aws_cloudwatch_event_rule.host_read_ads_event_past_due.name
  target_id = "${var.environment}-podcast-host-read-ads-past-due-notifications"
  arn       = module.lambda_podcast_notification.lambda_arn
  input     = "{\"eventType\": \"ad-past-due\"}"
}

resource "aws_lambda_permission" "allow_cloudwatch_host_read_ads_event_past_due" {
  statement_id  = "AllowHostReadAdsPastDueExecutionFromCloudWatch"
  action        = "lambda:InvokeFunction"
  function_name = module.lambda_podcast_notification.lambda_name
  principal     = "events.amazonaws.com"
  source_arn    = aws_cloudwatch_event_rule.host_read_ads_event_past_due.arn
}


resource "aws_cloudwatch_event_rule" "scheduled_episodes_event" {
  name                = "${var.environment}-podcast-scheduled-episodes-notifications"
  description         = "Event for sending emails about scheduled episodes that will go live in the next 24 hours"
  schedule_expression = "rate(1 hour)"
}

resource "aws_cloudwatch_event_target" "scheduled_episodes_event_target" {
  rule      = aws_cloudwatch_event_rule.scheduled_episodes_event.name
  target_id = "${var.environment}-podcast-scheduled-episodes-notifications"
  arn       = module.lambda_podcast_notification.lambda_arn
  input     = "{\"eventType\": \"episode-going-live-tomorrow\"}"
}

resource "aws_lambda_permission" "allow_cloudwatch_scheduled_episodes_event" {
  statement_id  = "AllowScheduledEpisodeExecutionFromCloudWatch"
  action        = "lambda:InvokeFunction"
  function_name = module.lambda_podcast_notification.lambda_name
  principal     = "events.amazonaws.com"
  source_arn    = aws_cloudwatch_event_rule.scheduled_episodes_event.arn
}


resource "aws_cloudwatch_event_rule" "scheduled_episodes_gone_live_event" {
  name                = "${var.environment}-podcast-episodes-gone-live-notifications"
  description         = "Event for sending emails about scheduled episodes that went live in the last hour."
  schedule_expression = "rate(1 hour)"
}

resource "aws_cloudwatch_event_target" "scheduled_episodes_gone_live_event_target" {
  rule      = aws_cloudwatch_event_rule.scheduled_episodes_gone_live_event.name
  target_id = "${var.environment}-podcast-episodes-gone-live-notifications"
  arn       = module.lambda_podcast_notification.lambda_arn
  input     = "{\"eventType\": \"episodes-gone-live\"}"
}

resource "aws_lambda_permission" "allow_cloudwatch_scheduled_episodes_gone_live_event" {
  statement_id  = "AllowScheduledEpisodesGoneLiveExecutionFromCloudWatch"
  action        = "lambda:InvokeFunction"
  function_name = module.lambda_podcast_notification.lambda_name
  principal     = "events.amazonaws.com"
  source_arn    = aws_cloudwatch_event_rule.scheduled_episodes_gone_live_event.arn
}


# transcribe lambda
module "lambda_podcast_transcribe_sentry" {
  source              = "git@github.com:theorchard/terraform-sentry.git//?ref=2.0.1"
  service_name        = var.lambda_transcribe_name
  environment         = var.environment
  application_family  = var.application_family
  team                = var.environment
  platform            = "python"
}

module "lambda_podcast_transcribe_owsrequest" {
  source = "git@github.com:theorchard/terraform-owsrequest.git//?ref=1.0.0"

  environment_name = var.environment
  service_name     = var.lambda_transcribe_name
}

data "aws_iam_policy_document" "transcribe_policy" {
  statement {
    actions = [
      "transcribe:GetTranscriptionJob"
    ]
    effect    = "Allow"
    resources = ["*"]
  }
}

resource "aws_iam_policy" "transcribe_policy" {
  name   = "${var.environment}-lambda-podcast-transcribe-policy"
  policy = data.aws_iam_policy_document.transcribe_policy.json
}

module "lambda_podcast_transcribe" {
  source                   = "git@github.com:theorchard/terraform-lambda.git//?ref=1.3.3"
  lambda_name              = var.lambda_transcribe_name
  lambda_description       = "Lambda that responds to transcribe job events and sends transcriptions results to ows-podcast."
  use_custom_function_name = true
  custom_function_name     = "${var.lambda_transcribe_name}-${var.environment}"
  environment              = var.environment
  application_family       = var.application_family
  lambda_function_timeout  = 300

  datadog_enabled = false

  lambda_function_environment_variables = {
    ENVIRONMENT            = var.environment,
    INPUT_BUCKET           = "dev-orcd-asset-transcoder-input"
    OUTPUT_BUCKET          = "dev-orcd-podcast-output-assets"
    OWSREQUEST_SERVICE_MAP = "{\"ows-podcast\": \"dev-ows-podcast.dev.theorchard.io\"}"
  }

  iam_managed_policy_attachments = [
    module.lambda_podcast_transcribe_owsrequest.policy_arn_output,
    aws_iam_policy.transcribe_policy.arn,
    "arn:aws:iam::103233932089:policy/S3-dev-orcd-podcast-output-assets-RW",
    "arn:aws:iam::103233932089:policy/dev-asset-transcoder-input-bucket-readwrite-policy"
  ]
}

data "template_file" "input_asset_event_definition" {
  template = file("${path.module}/${var.cloudwatch_event_rule_pattern_file}")
}

# Event rule for Transcribe state changes.
resource "aws_cloudwatch_event_rule" "transcribe_complete_event_rule" {
  name          = "${var.environment}-podcast-transcribe-finished-rule"
  description   = "The CloudWatch event rule for transcribe change states"
  event_pattern = data.template_file.input_asset_event_definition.rendered
}

resource "aws_cloudwatch_event_target" "transcribe_lambda_target" {
  rule      = aws_cloudwatch_event_rule.transcribe_complete_event_rule.name
  target_id = "${var.environment}_transcribe_podcast_rule_target"
  arn       = module.lambda_podcast_transcribe.lambda_arn
}

resource "aws_lambda_permission" "allow_cloudwatch_transcribe_event" {
  statement_id  = "AllowExecutionFromTranscribeEvent"
  action        = "lambda:InvokeFunction"
  function_name = module.lambda_podcast_transcribe.lambda_name
  principal     = "events.amazonaws.com"
  source_arn    = aws_cloudwatch_event_rule.transcribe_complete_event_rule.arn
}

# chartable lambda
module "lambda_podcast_chartable_sentry" {
  source              = "git@github.com:theorchard/terraform-sentry.git//?ref=2.0.1"
  service_name        = var.lambda_chartable_name
  environment         = var.environment
  application_family  = var.application_family
  team                = var.environment
  platform            = "python"
}

module "lambda_podcast_chartable_owsrequest" {
  source = "git@github.com:theorchard/terraform-owsrequest.git//?ref=1.0.0"

  environment_name = var.environment
  service_name     = var.lambda_chartable_name
}

module "lambda_podcast_chartable" {
  source                   = "git@github.com:theorchard/terraform-lambda.git//?ref=1.3.3"
  lambda_name              = var.lambda_chartable_name
  lambda_description       = "Lambda scheduled daily to trigger sentry notifications for missing chartable files."
  environment              = var.environment
  application_family       = var.application_family
  lambda_function_timeout  = 300
  use_container_image      = true
  datadog_enabled = false

  cloudwatch_event_enabled  = true
  cloudwatch_event_schedule = "cron(0 21 * * ? *)" # Every day at 9PM UTC

  lambda_function_environment_variables = {
    ENVIRONMENT            = var.environment,
    CHARTABLE_BUCKET       = "dev-orcd-podcast-chartable"
    OWSREQUEST_SERVICE_MAP = "{\"ows-podcast\": \"dev-ows-podcast.dev.theorchard.io\"}"
  }

  iam_managed_policy_attachments = [
    module.lambda_podcast_chartable_owsrequest.policy_arn_output,
    "arn:aws:iam::103233932089:policy/S3-dev-orcd-podcast-chartable-RW"
  ]
}
