# LocalStack Development Environment with Terraform
# Uses local mirrored terraform configurations

include .env

.PHONY: help start stop logs status clean verify \
	tf-init tf-plan tf-apply tf-destroy tf-output tf-clean \
	check projects deploy-all up \
	outbox-invoke outbox-logs outbox-events handler-logs outbox-status

# Project selection (lambda-abacus, lambda-av-scan, etc)
# PROJECT is sourced from .env

# Local terraform directory
TERRAFORM_DIR=./terraform/$(PROJECT)

help:
	@echo "LocalStack + Terraform Development Environment"
	@echo ""
	@echo "Current Project: $(PROJECT)"
	@echo "Terraform dir: $(TERRAFORM_DIR)"
	@echo ""
	@echo "Setup:"
	@echo "  make check           - Check prerequisites are installed"
	@echo "  make projects        - List available projects"
	@echo ""
	@echo "Combined Workflows:"
	@echo "  make deploy-all      - Deploy all projects in dependency order"
	@echo "  make up              - Start LocalStack + Deploy current PROJECT"
	@echo ""
	@echo "LocalStack Commands:"
	@echo "  make start           - Start LocalStack"
	@echo "  make stop            - Stop LocalStack"
	@echo "  make logs            - View LocalStack logs"
	@echo "  make status          - Check LocalStack status"
	@echo "  make verify          - Show deployed resources"
	@echo "  make clean           - Remove all data and stop containers"
	@echo ""
	@echo "Terraform Commands (single project; Set via .env or PROJECT=project_name):"
	@echo "  make tf-init         - Initialize Terraform with LocalStack"
	@echo "  make tf-plan         - Plan Terraform changes"
	@echo "  make tf-apply        - Apply Terraform (deploy to LocalStack)"
	@echo "  make tf-destroy      - Destroy all Terraform resources"
	@echo "  make tf-output       - Show Terraform outputs"
	@echo ""

# LocalStack Commands
start:
	@echo "Starting LocalStack..."
	docker compose up -d
	@echo "Waiting for LocalStack to be ready..."
	@sleep 15
	@$(MAKE) status

stop:
	@echo "Stopping LocalStack..."
	docker compose down

logs:
	docker compose logs -f localstack

status:
	@echo "=== LocalStack Status ==="
	@aws --endpoint-url=http://localhost:4566 s3 ls 2>/dev/null \
		&& echo "S3 ready" || echo "S3 not ready"
	@aws --endpoint-url=http://localhost:4566 lambda list-functions \
		--query 'Functions[*].FunctionName' --output table 2>/dev/null \
		|| echo "Lambda not ready"
	@aws --endpoint-url=http://localhost:4566 stepfunctions list-state-machines \
		--query 'stateMachines[*].name' --output table 2>/dev/null \
		|| echo "Step Functions not ready"

verify:
	@echo "=== Deployed Resources in LocalStack ==="
	@echo ""
	@echo "S3 Buckets:"
	@aws --endpoint-url=http://localhost:4566 s3 ls 2>/dev/null || echo "  (none or service not ready)"
	@echo ""
	@echo "Lambda Functions:"
	@aws --endpoint-url=http://localhost:4566 lambda list-functions \
		--query 'Functions[*].[FunctionName,Runtime,LastModified]' \
		--output table 2>/dev/null || echo "  (none or service not ready)"
	@echo ""
	@echo "Step Functions:"
	@aws --endpoint-url=http://localhost:4566 stepfunctions list-state-machines \
		--query 'stateMachines[*].[name,creationDate]' \
		--output table 2>/dev/null || echo "  (none or service not ready)"
	@echo ""
	@echo "SQS Queues:"
	@aws --endpoint-url=http://localhost:4566 sqs list-queues \
		--query 'QueueUrls' --output table 2>/dev/null || echo "  (none or service not ready)"
	@echo ""
	@echo "SNS Topics:"
	@aws --endpoint-url=http://localhost:4566 sns list-topics \
		--query 'Topics[*].TopicArn' --output table 2>/dev/null || echo "  (none or service not ready)"
	@echo ""
	@echo "EventBridge Rules:"
	@aws --endpoint-url=http://localhost:4566 events list-rules \
		--query 'Rules[*].[Name,State,ScheduleExpression]' \
		--output table 2>/dev/null || echo "  (none or service not ready)"

clean:
	@echo "Cleaning LocalStack data..."
	docker compose down -v
	rm -rf volume/
	rm -rf terraform/*/.terraform
	rm -rf terraform/*/terraform.tfstate*
	rm -rf terraform/*/.terraform.lock.hcl
	rm -rf terraform/*/_override.tf
	@echo "Cleaned"

# Terraform Commands
tf-init:
	@echo "Initializing Terraform for $(PROJECT)..."
	@if [ ! -d "$(TERRAFORM_DIR)" ]; then \
		echo "Error: Project directory not found: $(TERRAFORM_DIR)"; \
		echo "Available projects:"; \
		ls -1 terraform/ | sed 's/^/  - /'; \
		exit 1; \
	fi
	@if [ ! -f "$(TERRAFORM_DIR)/_override.tf" ]; then \
		echo "Creating Terraform override..."; \
		ln -sf $(PWD)/terraform/_shared/provider_override.tf $(TERRAFORM_DIR)/_override.tf; \
	fi
	@cd $(TERRAFORM_DIR) && terraform init -reconfigure

tf-plan:
	@echo "Planning Terraform changes for $(PROJECT)..."
	@cd $(TERRAFORM_DIR) && terraform plan

tf-apply:
	@echo "Applying Terraform for $(PROJECT) to LocalStack..."
	@cd $(TERRAFORM_DIR) && terraform apply -auto-approve
	@echo ""
	@echo "Resources deployed to LocalStack"
	@$(MAKE) tf-output

tf-destroy:
	@echo "Destroying Terraform resources for $(PROJECT)..."
	@cd $(TERRAFORM_DIR) && terraform destroy -auto-approve

tf-output:
	@echo "=== Terraform Outputs for $(PROJECT) ==="
	@cd $(TERRAFORM_DIR) && terraform output 2>/dev/null || echo "  (no outputs)"

# Cleanup
tf-clean:
	@echo "Removing Terraform state and overrides..."
	@rm -f $(TERRAFORM_DIR)/_override.tf
	@rm -f $(TERRAFORM_DIR)/terraform.tfstate*
	@rm -f $(TERRAFORM_DIR)/.terraform.lock.hcl
	@rm -rf $(TERRAFORM_DIR)/.terraform
	@echo "Cleaned $(PROJECT)"

# Check prerequisites
check:
	@./scripts/check-prerequisites.sh

# List available projects
projects:
	@echo "Available projects:"
	@ls -1 terraform/ | grep -v "^_" | sed 's/^/  - /'
	@echo ""
	@echo "Current: $(PROJECT)"

# Deploy everything in correct order
deploy-all:
	@./scripts/deploy-all.sh

# Combined workflow (single project)
up: start
	@echo ""
	@$(MAKE) tf-init
	@$(MAKE) tf-apply

## Outbox Testing Commands
outbox-invoke: ## Manually invoke outbox processor Lambda
	@echo "Invoking outbox processor Lambda..."
	@aws --endpoint-url=http://localhost:4566 lambda invoke \
		--function-name $(ENVIRONMENT)-outbox-processor \
		--payload '{}' \
		/tmp/outbox-response.json 2>/dev/null
	@cat /tmp/outbox-response.json | jq .
	@rm /tmp/outbox-response.json

outbox-logs: ## View outbox processor logs
	@echo "=== Outbox Processor Logs ==="
	@aws --endpoint-url=http://localhost:4566 logs tail \
		/aws/lambda/$(ENVIRONMENT)-outbox-processor \
		--follow 2>/dev/null || echo "No logs available yet"

outbox-events: ## View outbox events log
	@echo "=== Outbox Events Log ==="
	@aws --endpoint-url=http://localhost:4566 logs tail \
		/aws/events/$(ENVIRONMENT)-outbox-events \
		--follow 2>/dev/null || echo "No events logged yet"

handler-logs: ## View file upload handler logs
	@echo "=== File Upload Handler Logs ==="
	@aws --endpoint-url=http://localhost:4566 logs tail \
		/aws/lambda/$(ENVIRONMENT)-file-upload-handler \
		--follow 2>/dev/null || echo "No logs available yet"

outbox-status: ## Check outbox processing status
	@echo "=== Outbox Processor Status ==="
	@echo ""
	@echo "Lambda Functions:"
	@aws --endpoint-url=http://localhost:4566 lambda list-functions \
		--query 'Functions[?contains(FunctionName, `outbox`) || contains(FunctionName, `handler`)].FunctionName' \
		--output table 2>/dev/null
	@echo ""
	@echo "EventBridge Rules:"
	@aws --endpoint-url=http://localhost:4566 events list-rules \
		--query 'Rules[?contains(Name, `outbox`) || contains(Name, `file-upload`)].{Name:Name,State:State}' \
		--output table 2>/dev/null
	@echo ""
	@echo "Recent Lambda Invocations:"
	@echo "  (Check CloudWatch Logs for details)"
