SHELL := /bin/sh
COMPOSE := docker compose --env-file .env.production
BACKUP_DIR ?= backups

.PHONY: setup guard-env audit-production migrate test deploy backup restore-drill compose-up compose-down logs clean-macos

setup:
	test -f .env.production || cp .env.production.example .env.production
	mkdir -p secrets/wechatpay $(BACKUP_DIR)
	test -f secrets/alertmanager_token || printf '%s\n' 'replace-with-alertmanager-token' > secrets/alertmanager_token
	$(COMPOSE) build

guard-env:
	test -f .env.production

audit-production: guard-env
	node backend/scripts/production-env-audit.mjs .env.production
	node scripts/audit-production-sentinels.mjs
	$(COMPOSE) config --quiet

migrate: audit-production
	$(COMPOSE) build backend
	$(COMPOSE) up -d postgres minio minio-init
	$(COMPOSE) stop caddy web backend || true
	$(COMPOSE) run --rm backend npm run db:migrate:lite
	$(COMPOSE) up -d backend web caddy

test:
	cd backend && npm run typecheck && npm run prisma:validate && npm run test
	cd web && npm run lint && npm run build && npm run test:e2e
	cd miniapp && npm run typecheck && npm run build:weapp

deploy: audit-production
	$(COMPOSE) pull || true
	$(COMPOSE) build
	$(COMPOSE) up -d postgres minio minio-init
	$(COMPOSE) stop caddy web backend || true
	$(COMPOSE) run --rm backend npm run db:migrate:lite
	$(COMPOSE) up -d
	$(COMPOSE) ps

backup: guard-env
	@ts=$$(date +%Y%m%d-%H%M%S); \
	mkdir -p "$(BACKUP_DIR)/$$ts"; \
	$(COMPOSE) exec -T postgres sh -c 'pg_dump -U "$$POSTGRES_USER" "$$POSTGRES_DB"' > "$(BACKUP_DIR)/$$ts/postgres.sql"; \
	$(COMPOSE) exec -T minio sh -c 'tar -C /data -czf - .' > "$(BACKUP_DIR)/$$ts/minio-data.tgz"; \
	echo "backup written to $(BACKUP_DIR)/$$ts"

restore-drill:
	@echo "Restore drill is documented in docs/BACKUP_RESTORE.md. Run it on a staging copy, never on production first."

compose-up:
	$(COMPOSE) up -d

compose-down:
	$(COMPOSE) down

logs:
	$(COMPOSE) logs -f --tail=200

clean-macos:
	find . -depth \( -name '._*' -o -name '.DS_Store' \) -delete
