import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
import { mesh, parseEnvFromStack } from "@mesh-tech/infra-components";

// ============================================================================
// Configuration
// ============================================================================

const config = new pulumi.Config("mesh");
const awsConfig = new pulumi.Config("aws");

const tenant = config.require("tenant");
const region = awsConfig.require("region");
const env = parseEnvFromStack(tenant);
const pulumiStateBucket = config.require("pulumiStateBucket");

// Get AWS account ID
const callerIdentity = await aws.getCallerIdentity();
const awsAccountId = callerIdentity.accountId;

// ============================================================================
// Core Infrastructure
// ============================================================================
// MeshCore creates:
// - VPC with public/private subnets (calculated from vpc.cidr)
// - EKS cluster (if eks config provided)
// - RDS instance (if rds config provided)
// - Peering IAM role (if peering.allowPeeringFrom provided)
// - Auto-exports to SSM: /mesh/{tenant}/{env}/core
//

const meshCore = new mesh.layers.MeshCore("core", {
  tenant,
  env,
  region,
  awsAccountId,
  pulumiStateBucket,
  vpc: config.requireObject("vpc"),
  eks: config.getObject("eks") ?? false,
  rds: config.getObject("rds") ?? false,
  rdsBastion: config.getObject("rdsBastion") ?? config.getBoolean("rdsBastion") ?? false,
  peering: config.getObject("peering"),
  dns: config.getObject("dns"),
  externalTenants: config.getObject("externalTenants"),
  // serviceMesh: false to disable, object to configure, undefined for defaults
  serviceMesh: config.get("serviceMesh") === "false" ? false : config.getObject("serviceMesh"),
  // Secrets (set via: pulumi config set --secret mesh:newRelicLicenseKey <key>)
  newRelicLicenseKey: config.getSecret("newRelicLicenseKey"),
});

// ============================================================================
// Stack Exports
// ============================================================================
// These are available via `pulumi stack output`

export const stack = pulumi.getStack();
export const tenantName = tenant;
export const environment = env;
export const accountId = awsAccountId;

// All core infrastructure outputs (includes VPC, EKS, RDS, IAM, peering, ssmPath)
export const core = meshCore.outputs;
