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

############################################
# Load FastAPI Terraform State
############################################
data "terraform_remote_state" "fast_api" {
  backend = "s3"
  config = {
    bucket = "ara-fast-api-terraform-state"
    key    = "env:/${var.stage}/terraform.tfstate"
    region = "eu-west-2"
  }
}

############################################
# Load CDN Certificate Terraform State
############################################
data "terraform_remote_state" "cdn_certificate" {
  backend = "s3"
  config = {
    bucket = "cdn-certificate-terraform-state"
    key    = "env:/${var.stage}/terraform.tfstate"
    region = "eu-west-2"
  }
}

############################################
# CloudFront for API
############################################
module "cdn" {
  source = "../modules/cloudfront"

  aliases = [data.terraform_remote_state.fast_api.outputs.domain_name]

  acm_certificate_arn = data.terraform_remote_state.cdn_certificate.outputs.certificate_arn

  origins = [
    # ---- S3 ----
    {
      origin_type        = "s3"
      origin_domain_name = data.terraform_remote_state.shared.outputs.retrofit_datalake_bucket_domain_name
      origin_id          = "s3-origin"
      bucket_id          = data.terraform_remote_state.shared.outputs.retrofit_datalake_bucket_id
      bucket_arn         = data.terraform_remote_state.shared.outputs.retrofit_datalake_bucket_arn
    },

    # ---- API Gateway ----
    {
      origin_type        = "api"
      origin_domain_name = replace(data.terraform_remote_state.fast_api.outputs.invoke_url, "/^https?://([^/]*).*/", "$1")
      origin_id = "api-origin"
    }
  ]
}