module "main_iam_profiles" {
  source      = "../../../modules/iam/default_instance_profiles"
  name_prefix = local.name_prefix
}

# Consumer IAM role with cross-env bucket access
module "s3_aggregated_stream_reports_rw" {
  source = "../../../modules/iam/policies/s3/buckets_rw"

  name         = "s3_aggregated_stream_reports_rw"
  name_prefix  = local.name_prefix
  bucket_masks = ["dev-sme-aggregated-stream-reports"]
}

module "s3_win_jobs_rw_policy" {
  source = "../../../modules/iam/policies/s3/buckets_rw"

  name        = "s3_win_jobs_rw_policy"
  name_prefix = local.name_prefix

  bucket_masks = [
    "${local.name_prefix}-*",
    "${local.env_prefix}-sme-stream-reports",
    "${local.env_prefix}-sme-aggregated-stream-reports",
    "${local.env_prefix}-sme-datalake",
  ]
}

module "s3_delphi_dataarchive_ro" {
  source = "../../../modules/iam/policies/s3/buckets_ro"

  name        = "s3_delphi_dataarchive_ro"
  name_prefix = local.name_prefix
  bucket_masks = [
    "stage-sme-data-archive",
    "sme-data-archive"
  ]
}

module "ec2_win_jobs_role" {
  source = "../../../modules/iam/roles/ec2_instance_role"

  name_prefix = local.name_prefix
  name        = "win_jobs_role"

  common_tags = merge(
    local.common_tags,
    {
      project                  = "ETL",
      service                  = "EC2",
      plat_env_project_service = "${local.aggregated_tag}_ETL_EC2"
    }
  )

  policies_list = [
    module.s3_win_jobs_rw_policy.policy.arn,
    "arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy",
  ]
}

module "vendor_image_caching_s3_rw_policy" {
  source = "../../../modules/iam/policies/s3/buckets_rw"

  name        = "vendor-image-caching"
  name_prefix = local.name_prefix

  bucket_masks = [
    module.vendor_image_caching_bucket.bucket.id,
  ]
}

module "cross_account_notifications_role" {
  source      = "../../../modules/iam/roles/cross_account_role"
  name        = "${local.name_prefix}-cross_account_notifications_role"
  common_tags = local.common_tags
  require_mfa = false
  principal_list = [
    format("arn:aws:iam::%s:role/${var.platform["prefix"]}-delphi-dae-s3-consumer-events-distribution-lambda-role", module.aws_accounts_list.accounts["gdb-delphi-dev"]),
  ]
  policies_list = [
    module.notifications_s3_rw_policy.policy.arn,
    module.notifications_delphi_s3_ro_policy.policy.arn,
  ]
}

module "notifications_s3_rw_policy" {
  source = "../../../modules/iam/policies/s3/buckets_rw"

  name        = "s3-crossaccount-notifications-rw"
  name_prefix = local.name_prefix

  bucket_masks = [
    module.apollo_notifications_bucket.bucket.id,
  ]
}

module "notifications_delphi_s3_ro_policy" {
  source      = "../../../modules/iam/policies/s3/buckets_ro"
  name        = "s3-delphi-notifications-ro"
  name_prefix = local.name_prefix

  bucket_masks = [
    "${local.env_prefix}-delphi-notifications"
  ]
}

data "aws_iam_policy_document" "run_ecs_task" {
  statement {
    actions   = ["iam:PassRole"]
    effect    = "Allow"
    resources = ["*"]
    condition {
      test     = "StringEquals"
      variable = "iam:PassedToService"
      values = [
        "ec2.amazonaws.com",
        "ecs-tasks.amazonaws.com"
      ]
    }
  }
  statement {
    actions   = ["ecs:RunTask"]
    effect    = "Allow"
    resources = ["arn:aws:ecs:*:${local.account_id}:task-definition/${local.name_prefix}*:*"]
    condition {
      test     = "ArnLike"
      variable = "ecs:cluster"
      values   = ["arn:aws:ecs:${var.aws_region_id}:${local.account_id}:cluster/${local.name_prefix}-*"]
    }
  }
  statement {
    actions   = ["ecs:ListTasks"]
    effect    = "Allow"
    resources = ["*"]
    condition {
      test     = "ArnLike"
      variable = "ecs:cluster"
      values   = ["arn:aws:ecs:${var.aws_region_id}:${local.account_id}:cluster/${local.name_prefix}-*"]
    }
  }
}

resource "aws_iam_policy" "run_ecs_task" {
  name        = "${local.name_prefix}-run_ecs_tasks"
  description = "Allows to run and list ECS tasks in ${local.name_prefix}-clu ECS cluster."
  policy      = data.aws_iam_policy_document.run_ecs_task.json
}

module "ecs_scheduler_role" {
  source      = "../../../modules/iam/roles/cloudwatch_role"
  name_prefix = local.name_prefix
  name        = "ecs_scheduler_role"
  common_tags = local.common_tags
  policies_list = [
    aws_iam_policy.run_ecs_task.arn
  ]
}

module "ecs_task_runner_role" {
  source        = "../../../modules/iam/roles/ecs_task_role"
  name_prefix   = local.name_prefix
  name          = "ecs_task_execution_role"
  policies_list = [module.kms_secrets_manager.secrets_deployment_ro_policy.arn]
}

module "logging_policy" {
  source      = "../../../modules/iam/policies/logging"
  name_prefix = local.name_prefix
}

module "admin_panel_assets_s3_rw_policy" {
  source = "../../../modules/iam/policies/s3/buckets_rw"

  name        = "admin_panel_assets_rw"
  name_prefix = local.name_prefix

  bucket_masks = [
    module.admin_panel_assets.bucket.id,
  ]
}

data "aws_iam_policy_document" "notifications_sns_publish_policy_doc" {
  statement {
    actions   = ["sns:Publish"]
    effect    = "Allow"
    resources = [module.notifications_sns_topic.topic.arn]
  }
  statement {
    actions = [
      "kms:GenerateDataKey",
      "kms:Decrypt",
    ]
    effect    = "Allow"
    resources = [data.aws_kms_key.default_sns_key.arn]
  }
}

resource "aws_iam_policy" "notifications_sns_publish_policy" {
  name        = "${local.name_prefix}-publish_notifications"
  description = "Allows publish notifications to SNS topic."
  policy      = data.aws_iam_policy_document.notifications_sns_publish_policy_doc.json
}

data "aws_iam_policy_document" "push_messages_sns_publish_policy_doc" {
  statement {
    actions   = ["sns:Publish"]
    effect    = "Allow"
    resources = [module.push_messages_sns_topic.topic.arn]
  }
  statement {
    actions = [
      "kms:GenerateDataKey",
      "kms:Decrypt",
    ]
    effect    = "Allow"
    resources = [data.aws_kms_key.default_sns_key.arn]
  }
}

resource "aws_iam_policy" "push_messages_sns_publish_policy" {
  name        = "${local.name_prefix}-publish_push_messages"
  description = "Allows publish notifications to SNS topic."
  policy      = data.aws_iam_policy_document.push_messages_sns_publish_policy_doc.json
}

data "aws_iam_policy_document" "messages_sns_publish_policy_doc" {
  statement {
    actions   = ["sns:Publish"]
    effect    = "Allow"
    resources = [module.messages_sns_topic.topic.arn]
  }
  statement {
    actions = [
      "kms:GenerateDataKey",
      "kms:Decrypt",
    ]
    effect    = "Allow"
    resources = [data.aws_kms_key.default_sns_key.arn]
  }
}

resource "aws_iam_policy" "messages_sns_publish_policy" {
  name        = "${local.name_prefix}-publish_messages"
  description = "Allows publish messages to SNS topic."
  policy      = data.aws_iam_policy_document.messages_sns_publish_policy_doc.json
}


module "etl_ro_s3_policies" {
  source = "../../../modules/iam/policies/s3/buckets_ro"

  name        = "etl_ro"
  name_prefix = local.name_prefix

  bucket_masks = [
    "${local.env_prefix}-sme-aggregated-stream-reports",
    "${local.env_prefix}-sme-stream-reports",
    "${local.name_prefix}-export-playlists-daily",
    module.jobs_responses_bucket.bucket.id,
    module.filtr_spotify_browse_export_bucket.bucket.id,
    module.data_dumps_bucket.bucket.id,
    module.filtrmoodagent_bucket.bucket.id,
  ]
}

module "etl_rw_s3_policies" {
  source = "../../../modules/iam/policies/s3/buckets_rw"

  name        = "etl_rw"
  name_prefix = local.name_prefix

  bucket_masks = [
    "${local.env_prefix}-sme-aggregated-stream-reports",
    "${local.env_prefix}-sme-stream-reports",
    "${local.name_prefix}-export-playlists-daily",
    module.jobs_responses_bucket.bucket.id,
    "filtr-spotify-browse-export",
    "apollo-data-dumps",
    "filtrmoodagent",
    "${local.env_prefix}-sony-editorialimages",
    module.filtr_spotify_browse_export_bucket.bucket.id,
    module.data_dumps_bucket.bucket.id,
    module.filtrmoodagent_bucket.bucket.id,
    module.filtr_new_releases.bucket.id,
    module.filtr_new_releases_upc.bucket.id,
    "sme-spotify-top-reports",
    "sme.ca.prod.smanalytics.partners",
  ]
}

module "iam_auth0_log_ids_policy" {
  source = "../../../modules/iam/policies/s3/buckets_rw"

  bucket_masks = [module.auth0_log_offset_bucket.bucket.id]
  name         = "auth0_log_offset_rw"
  name_prefix  = local.name_prefix
}

module "spotify_charts_s3_rw_policy" {
  source = "../../../modules/iam/policies/s3/buckets_rw"

  name        = "spotify-charts-s3-rw"
  name_prefix = local.name_prefix

  bucket_masks = [
    module.s3-spotify_charts.bucket.id,
  ]
}


module "logs_db_access_policy" {
  source = "../../../modules/iam/policies/athena"

  name_prefix = local.name_prefix
  policy_name = "logs_db_access"

  athena_workspaces_arns = [
    "arn:aws:athena:${var.aws_region_id}:${local.account_id}:workgroup/primary",
  ]

  glue_resources_arns = [
    "arn:aws:glue:${var.aws_region_id}:${local.account_id}:catalog",
    "arn:aws:glue:${var.aws_region_id}:${local.account_id}:database/${local.logs_athena_db}",
    "arn:aws:glue:${var.aws_region_id}:${local.account_id}:table/${local.logs_athena_db}/*",
  ]
}

resource "aws_iam_role_policy_attachment" "cross_account_deployment_to_logs_db" {
  policy_arn = module.logs_db_access_policy.this.arn
  role       = data.aws_iam_role.cross_account_deployment.name
}

data "aws_iam_role" "cross_account_qa_role" {
  name = "cross_account_qa"
}

resource "aws_iam_role_policy_attachment" "test_delphi_notifications" {
  for_each = toset([
    module.sqs_delphi_notification_iam_policies.consumer_policy.arn,
    module.sqs_delphi_notification_iam_policies.producer_policy.arn
  ])

  role       = data.aws_iam_role.cross_account_qa_role.name
  policy_arn = each.key
}

module "load_testing_config_ro_s3_policies" {
  source = "../../../modules/iam/policies/s3/buckets_ro"

  name        = "load_testing_config_ro"
  name_prefix = local.name_prefix

  bucket_masks = [
    module.s3_load_testing_config.bucket.id,
  ]
}

module "load_testing_config_rw_s3_policies" {
  source = "../../../modules/iam/policies/s3/buckets_rw"

  name        = "load_testing_config_rw"
  name_prefix = local.name_prefix

  bucket_masks = [
    module.s3_load_testing_config.bucket.id,
  ]
}

resource "aws_iam_role_policy_attachment" "cross_account_deployment_to_load_testing_config" {
  policy_arn = module.load_testing_config_ro_s3_policies.policy.arn
  role       = data.aws_iam_role.cross_account_deployment.name
}

resource "aws_iam_role_policy_attachment" "cross_account_developer_to_load_testing_config" {
  policy_arn = module.load_testing_config_rw_s3_policies.policy.arn
  role       = data.aws_iam_role.cross_account_deployment.name
}
