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 "lambda" {
  source = "../../modules/lambda_with_sqs"

  name  = "pashub_to_ara"
  stage = var.stage

  image_uri = local.image_uri

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

  reserved_concurrent_executions = var.reserved_concurrent_executions

  batch_size = var.batch_size

  environment = {
    STAGE = var.stage
    LOG_LEVEL = "info"
    
    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

    SHAREPOINT_CLIENT_ID                = var.sharepoint_client_id
    SHAREPOINT_CLIENT_SECRET            = var.sharepoint_client_secret
    SHAREPOINT_TENANT_ID                = var.sharepoint_tenant_id
    DOMNA_SHAREPOINT_ID                 = var.domna_sharepoint_id
    OSMOSIS_ACD_SHAREPOINT_ID           = var.osmosis_acd_sharepoint_id
    PRIVATE_PAY_SHAREPOINT_ID           = var.private_pay_sharepoint_id
    SOCIAL_HOUSING_WAVE_3_SHAREPOINT_ID = var.social_housing_wave_3_sharepoint_id
    PASHUB_EMAIL                        = var.pashub_email
    PASHUB_PASSWORD                     = var.pashub_password
    PASHUB_COORDINATION_EMAIL           = var.pashub_coordination_email
    PASHUB_COORDINATION_PASSWORD        = var.pashub_coordination_password
  }
}

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