resource "aws_sns_topic" "reminder_topic" {
  name = "reminders-${var.stage}"
  policy = <<EOF
{
  "Version": "2008-10-17",
  "Id": "__default_policy_ID",
  "Statement": [
    {
      "Sid": "__default_statement_ID",
      "Effect": "Allow",
      "Principal": {
        "AWS": "*"
      },
      "Action": [
        "SNS:Publish",
        "SNS:RemovePermission",
        "SNS:SetTopicAttributes",
        "SNS:DeleteTopic",
        "SNS:ListSubscriptionsByTopic",
        "SNS:GetTopicAttributes",
        "SNS:Receive",
        "SNS:AddPermission",
        "SNS:Subscribe"
      ],
      "Resource": "arn:aws:sns:us-east-1:679918342773:reminders",
      "Condition": {
        "StringEquals": {
          "AWS:SourceOwner": "679918342773"
        }
      }
    },
    {
      "Sid": "__console_pub_0",
      "Effect": "Allow",
      "Principal": {
        "AWS": "*"
      },
      "Action": "SNS:Publish",
      "Resource": "arn:aws:sns:us-east-1:679918342773:reminders"
    }
  ]
}
EOF
}

resource "aws_sns_topic_subscription" "send_reminders_to_service" {
  topic_arn = "${aws_sns_topic.reminder_topic.arn}"
  protocol  = "https"
  endpoint  = "${var.base_url}/api/reminders/send"
  endpoint_auto_confirms = true
}

resource "aws_cloudwatch_event_rule" "scheduled_reminders" {
  name        = "send-scheduled-emails-${var.stage}"

  schedule_expression = "rate(4 hours)"
  role_arn = "${aws_iam_role.reminder_send_role.arn}"
}

resource "aws_cloudwatch_event_target" "sns" {
  rule      = "${aws_cloudwatch_event_rule.scheduled_reminders.name}"
  target_id = "SendToSNS"
  arn       = "${aws_sns_topic.reminder_topic.arn}"
}

resource "aws_iam_role" "reminder_send_role" {
  name = "reminder-send-role-${var.stage}"
  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "events.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
EOF
}

resource "aws_iam_role_policy_attachment" "allow_send" {
    role       = "${aws_iam_role.reminder_send_role.name}"
    policy_arn = "arn:aws:iam::aws:policy/AmazonSNSFullAccess"

}
