data "terraform_remote_state" "shared" {
  backend = "s3"
  config = {
    bucket = "assessment-model-terraform-state"
    key    = "env:/${var.stage}/terraform.tfstate"
    region = "eu-west-2"
  }
}

data "aws_secretsmanager_secret_version" "db_credentials" {
  secret_id = "${var.stage}/assessment_model/db_credentials"
}

locals {
  db_credentials = jsondecode(data.aws_secretsmanager_secret_version.db_credentials.secret_string)
}

resource "aws_iam_role_policy_attachment" "magic_plan_s3_write" {
  role       = module.lambda.role_name
  policy_arn = data.terraform_remote_state.shared.outputs.energy_assessments_s3_write_arn
}

module "lambda" {
  source = "../../modules/lambda_with_sqs"

  name  = "magic_plan"
  stage = var.stage

  image_uri = local.image_uri

  maximum_concurrency            = var.maximum_concurrency
  reserved_concurrent_executions = var.reserved_concurrent_executions
  batch_size                     = var.batch_size

  environment = {
    STAGE                 = var.stage
    LOG_LEVEL             = "info"
    MAGICPLAN_CUSTOMER_ID = var.magicplan_customer_id
    MAGICPLAN_API_KEY     = var.magicplan_api_key
    DB_USERNAME           = local.db_credentials.db_assessment_model_username
    DB_PASSWORD           = local.db_credentials.db_assessment_model_password
    DB_HOST               = var.db_host
    DB_NAME               = var.db_name
    DB_PORT               = var.db_port
  }
}
