terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }

  backend "s3" {
    bucket       = "autonomous-deployment-terraform-state"
    region       = "us-west-2"
    use_lockfile = true
  }
}

provider "aws" {
  profile = "default"
  region  = "us-west-2"
  alias   = "tf_state"
}

variable "env" {
  type = string
}

variable "controlplane_tenant_id" {
  type = string
}

variable "controlplane_subscription_id" {
  type = string
}

variable "controlplane_client_id" {
  type = string
}

data "aws_s3_object" "base_state" {
  bucket = "autonomous-deployment-terraform-state"
  key    = "aws/base/${var.env}.json"

  provider = aws.tf_state
}

locals {
  config              = yamldecode(file("${path.module}/config.yaml"))
  seed_default_values = try(local.config[var.env], null)
}

check "seed_required_defaults" {
  assert {
    condition     = try(local.seed_default_values.image_registry, "") != ""
    error_message = "No image_registry configured for this env in azure/account/seed."
  }

  assert {
    condition     = try(length(local.seed_default_values.admin_group_object_ids), 0) > 0
    error_message = "No admin_group_object_ids configured for this env in azure/account/seed."
  }

  assert {
    condition     = try(local.seed_default_values.acr_id_scope, "") != ""
    error_message = "No acr_id_scope configured for this env in azure/account/seed."
  }
}

output "env" {
  value = var.env
}

output "base_account" {
  value = jsondecode(data.aws_s3_object.base_state.body).outputs.account.value
}

output "controlplane_tenant_id" {
  value = var.controlplane_tenant_id
}

output "controlplane_subscription_id" {
  value = var.controlplane_subscription_id
}

output "controlplane_client_id" {
  value = var.controlplane_client_id
}

output "image_registry" {
  value = local.seed_default_values.image_registry
}

output "admin_group_object_ids" {
  value = local.seed_default_values.admin_group_object_ids
}

output "acr_id_scope" {
  value = local.seed_default_values.acr_id_scope
}
