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

# Reference the existing address2UPRN Lambda outputs from address2uprn state
data "terraform_remote_state" "address2uprn" {
  backend = "s3"
  config = {
    bucket = "address2uprn-terraform-state"
    key = "env:/${var.stage}/terraform.tfstate"
    region = "eu-west-2"
  }
}

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

  name  = "postcode-splitter"
  stage = var.stage

  image_uri = local.image_uri


  environment = merge(
    {
      STAGE     = var.stage
      LOG_LEVEL = "info"
      POSTGRES_USERNAME = local.db_credentials.db_assessment_model_username
      POSTGRES_PASSWORD = local.db_credentials.db_assessment_model_password
      ADDRESS2UPRN_QUEUE_URL = data.terraform_remote_state.address2uprn.outputs.address2uprn_queue_url
      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" "postcode_splitter_s3_read" {
  role       = module.lambda.role_name
  policy_arn = data.terraform_remote_state.shared.outputs.postcode_splitter_s3_read_arn
}

# Create SQS send policy for address2UPRN queue
module "postcode_splitter_sqs_policy" {
  source = "../../modules/general_iam_policy"

  policy_name        = "postcode-splitter-sqs-send-${var.stage}"
  policy_description = "Allow postcode-splitter Lambda to send messages to address2UPRN queue"

  actions = [
    "sqs:SendMessage"
  ]

  resources = [
    data.terraform_remote_state.address2uprn.outputs.address2uprn_queue_arn
  ]
}

# Attach SQS policy to the Lambda execution role
resource "aws_iam_role_policy_attachment" "postcode_splitter_sqs_send" {
  role       = module.lambda.role_name
  policy_arn = module.postcode_splitter_sqs_policy.policy_arn
}