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)
}

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

  name  = "address2uprn"
  stage = var.stage

  image_uri = local.image_uri

  timeout = 900

  # Optional: Set maximum_concurrency to limit concurrent SQS-triggered invocations (2-1000)
  maximum_concurrency = var.maximum_concurrency

  environment = merge(
    {
      STAGE     = var.stage
      LOG_LEVEL = "info"
      DB_USERNAME = local.db_credentials.db_assessment_model_username
      DB_PASSWORD = local.db_credentials.db_assessment_model_password
      S3_BUCKET_NAME = data.terraform_remote_state.shared.outputs.retrofit_sap_data_bucket_name
    },
  )
}

# Attach S3 read policy to the Lambda execution role
resource "aws_iam_role_policy_attachment" "address2uprn_read_and_write" {
  role       = module.address2uprn.role_name
  policy_arn = data.terraform_remote_state.shared.outputs.address_2_uprn_s3_read_and_write_arn
}