module "default_tags" {
  source             = "git@github.com:theorchard/terraform-default-tags.git//?ref=2.0.0"
  environment        = var.environment
  application_family = var.application_family
  service_name       = var.config_service_name
  team_name          = var.team_name
}

provider "aws" {
  region = var.aws_region

  default_tags {
    tags = module.default_tags.tags
  }
}

provider "aws" {
  region  = var.aws_region
  alias   = "networking"
  profile = "networking"

  default_tags {
    tags = module.default_tags.tags
  }
}

terraform {
  backend "s3" {
    bucket  = "orcd-terraform-state"
    key     = "prod/orchard-repo-cron-worker/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

data "aws_caller_identity" "current" {}

data "aws_s3_bucket" "config_bucket" {
  bucket = var.config_s3_bucket
}

data "aws_route53_zone" "route53_zone" {
  name = "theorchard.io"
}

module "vpc_info" {
  source = "git@github.com:theorchard/terraform-vpc-info.git//?ref=3.1.0"

  environment = var.environment
}

resource "aws_ecr_repository" "orchard_repo_cron_worker" {
  name                 = var.service_name
  image_tag_mutability = "MUTABLE"

  image_scanning_configuration {
    scan_on_push = true
  }

  encryption_configuration {
    encryption_type = "KMS"
  }

  tags = {
    environment        = var.environment
    service_name       = var.service_name
    application_family = var.application_family
    terraformed        = true
    map-migrated       = var.map_migrated_tag
  }
}

# Create KMS key and policies for certain encrypted configuration
resource "aws_kms_key" "orchard_repo_cron_worker_kms_key" {
  description             = "${var.environment}-${var.service_name}"
  enable_key_rotation     = true
  deletion_window_in_days = 30

  tags = {
    environment        = var.environment
    service_name       = var.service_name
    application_family = var.application_family
    terraformed        = true
    map-migrated       = var.map_migrated_tag
  }
}

resource "aws_kms_alias" "orchard_repo_cron_worker_kms_alias" {
  name          = "alias/${var.environment}-${var.service_name}"
  target_key_id = aws_kms_key.orchard_repo_cron_worker_kms_key.key_id
}

data "aws_iam_policy_document" "kms_decryption_policy" {
  statement {
    actions = [
      "kms:Decrypt",
      "kms:DescribeKey",
    ]

    resources = [
      aws_kms_key.orchard_repo_cron_worker_kms_key.arn,
    ]
  }
}

# Create KMS policy
resource "aws_iam_policy" "orchard_repo_cron_worker_kms_policy" {
  name   = "KMS-${var.environment}-${var.service_name}-policy"
  policy = data.aws_iam_policy_document.kms_decryption_policy.json
}

# Data resource for read-only policy to the S3 bucket
data "aws_iam_policy_document" "s3_configs_read_only_policy" {
  statement {
    actions = [
      "s3:GetBucketLocation",
      "s3:GetObject",
      "s3:ListBucket",
    ]

    resources = [
      "${data.aws_s3_bucket.config_bucket.arn}/${var.service_name}/${var.environment}/*",
    ]
  }

  statement {
    actions = [
      "s3:ListBucket",
    ]

    resources = [
      data.aws_s3_bucket.config_bucket.arn,
    ]
  }

  statement {
    actions = [
      "s3:GetBucketLocation",
      "s3:ListAllMyBuckets",
    ]

    resources = [
      "*",
    ]
  }
}

# Creates policy for read-only access to the S3 bucket. Intended to be used by ECS task roles in entrypoint scripts.
resource "aws_iam_policy" "s3_configs_read_only_policy" {
  name   = "S3-${var.environment}-${var.service_name}-RO"
  policy = data.aws_iam_policy_document.s3_configs_read_only_policy.json
}

data "aws_sns_topic" "accounting_debug_sns_topic" {
  name = "accounting_debug"
}

data "aws_iam_policy_document" "sns_policy_document" {
  statement {
    actions = [
      "sns:GetTopicAttributes",
      "sns:Publish",
    ]

    resources = [
      data.aws_sns_topic.accounting_debug_sns_topic.arn,
    ]
  }
}

# Create policy for SNS topics; used currently by accounting run
resource "aws_iam_policy" "sns_policy" {
  name   = "SNS-${var.environment}-accounting-debug-publish"
  policy = data.aws_iam_policy_document.sns_policy_document.json
}

resource "aws_iam_user" "user" {
  name = "${var.environment}-cron-user"
  tags = {
    role = "service-user"
  }
}

data "aws_iam_policy" "pre_existing_iam_policies" {
  for_each = toset(local.pre_existing_iam_policies)
  name     = each.value
}

resource "aws_iam_user_policy_attachment" "user_policy_attachment" {
  for_each   = data.aws_iam_policy.pre_existing_iam_policies
  user       = aws_iam_user.user.name
  policy_arn = each.value.arn
}

resource "aws_iam_user_policy_attachment" "user_sns_policy_attachment" {
  user       = aws_iam_user.user.name
  policy_arn = aws_iam_policy.sns_policy.arn
}

module "orchard_repo_cron_worker_cache" {
  source = "git@github.com:theorchard/terraform-elasticache.git//?ref=3.1.1"

  providers = {
    aws.dns = aws.networking
  }

  environment                = var.environment
  service_name               = var.service_name
  application_family         = var.application_family
  additional_tags            = { map-migrated = var.map_migrated_tag }
  cache_engine               = "memcached"
  memcached_engine_version   = "1.6.17"
  cache_parameter_group_name = "default.memcached1.6"
  cache_subnet_group_name    = "${var.environment}-elasticache-subnet-group"
  cache_node_count           = 1
  cache_node_type            = "cache.t4g.small"
  vpc_id                     = module.vpc_info.vpc_id
  route53_zone_id            = data.aws_route53_zone.route53_zone.zone_id
  additional_source_security_group_ids = [
    #     module.cron_jobs["bacon_youtube_claiming_agent_cron"].fargate_security_group_id
  ]
}

data "aws_elasticache_replication_group" "split_synchronizer_redis_cache" {
  replication_group_id = "${var.environment}-split-synchronizer"
}
