# Fractary Cloud Storage - Cloudflare R2
#
# This Terraform configuration creates an R2 bucket for Fractary Core
# file storage (docs and logs archival).
#
# Generated by: fractary-core config cloud-init --provider r2
#
# Usage:
#   cd infra/terraform
#   terraform init
#   terraform plan
#   terraform apply
#
# Prerequisites:
#   - Cloudflare API token with R2 permissions
#   - Set CLOUDFLARE_API_TOKEN environment variable

terraform {
  required_version = ">= 1.0"

  required_providers {
    cloudflare = {
      source  = "cloudflare/cloudflare"
      version = "~> 4.0"
    }
  }
}

provider "cloudflare" {
  api_token = var.cloudflare_api_token
}

# --- R2 Bucket ---

resource "cloudflare_r2_bucket" "fractary" {
  account_id = var.cloudflare_account_id
  name       = var.bucket_name
  location   = var.r2_location
}

# --- R2 API Token for Application Access ---
#
# Note: R2 uses S3-compatible API keys for bucket access.
# You can create these in the Cloudflare dashboard:
#   Dashboard > R2 > Manage R2 API Tokens > Create API Token
#
# Set the resulting credentials in .fractary/env/.env:
#   R2_ACCOUNT_ID=your_account_id
#   R2_ACCESS_KEY_ID=your_access_key
#   R2_SECRET_ACCESS_KEY=your_secret_key

# --- Lifecycle Rules ---
#
# R2 lifecycle rules are managed via the Cloudflare dashboard or API.
# Terraform support for R2 lifecycle rules is limited.
#
# Recommended manual configuration:
#   - Transition archived objects to Infrequent Access after 90 days
#   - No expiration (keep archives indefinitely)
#
# Dashboard path: R2 > {bucket} > Settings > Object lifecycle rules

# --- Outputs ---

output "bucket_name" {
  description = "The name of the Fractary R2 bucket"
  value       = cloudflare_r2_bucket.fractary.name
}

output "r2_endpoint" {
  description = "The S3-compatible endpoint for this R2 bucket"
  value       = "https://${var.cloudflare_account_id}.r2.cloudflarestorage.com"
}

output "account_id" {
  description = "The Cloudflare account ID"
  value       = var.cloudflare_account_id
}
