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  = "engine"
  stage = var.stage

  image_uri = local.image_uri

  maximum_concurrency = var.maximum_concurrency
  batch_size = var.batch_size
  timeout = var.timeout
  memory_size = var.memory_size

  environment = merge(
    {
      STAGE      = var.stage
      LOG_LEVEL  = "info"

      # DB from Secrets Manager
      DB_USERNAME = local.db_credentials.db_assessment_model_username
      DB_PASSWORD = local.db_credentials.db_assessment_model_password

      # Secrets from GitHub
      DB_HOST              = var.db_host
      DB_NAME              = var.db_name
      DB_PORT              = var.db_port
      API_KEY              = var.api_key
      SECRET_KEY           = var.secret_key
      EPC_AUTH_TOKEN       = var.epc_auth_token
      GOOGLE_SOLAR_API_KEY = var.google_solar_api_key

      # Buckets - from terraform state
      PLAN_TRIGGER_BUCKET             = data.terraform_remote_state.shared.outputs.retrofit_plan_trigger_bucket_name
      DATA_BUCKET                     = data.terraform_remote_state.shared.outputs.retrofit_sap_data_bucket_name
      SAP_PREDICTIONS_BUCKET          = data.terraform_remote_state.shared.outputs.retrofit_sap_predictions_bucket_name
      CARBON_PREDICTIONS_BUCKET       = data.terraform_remote_state.shared.outputs.retrofit_carbon_predictions_bucket_name
      HEAT_PREDICTIONS_BUCKET         = data.terraform_remote_state.shared.outputs.retrofit_heat_predictions_bucket_name
      HEATING_KWH_PREDICTIONS_BUCKET  = data.terraform_remote_state.shared.outputs.retrofit_heating_kwh_predictions_bucket_name
      HOTWATER_KWH_PREDICTIONS_BUCKET = data.terraform_remote_state.shared.outputs.retrofit_hotwater_kwh_predictions_bucket_name
      ENERGY_ASSESSMENTS_BUCKET       = data.terraform_remote_state.shared.outputs.retrofit_energy_assessments_bucket_name

      # SQS
      ENGINE_SQS_URL = "test" # Not actually needed by engine, only to satisfy Settings
 
      # Deployment
      ECR_URI    = var.ecr_repo_url
      GITHUB_SHA = var.image_digest
    }
  )
}

### Policies and IAM
# S3
resource "aws_iam_role_policy_attachment" "engine_s3_read_and_write" {
  role = module.lambda.role_name
  policy_arn = data.terraform_remote_state.shared.outputs.engine_s3_read_and_write_arn
}