.PHONY: dev stop migrate migrate-deploy db-push db-studio dev-node

ifneq (,$(wildcard .env))
include .env
export
endif

# Rust backend (default)
dev:
	@echo "Starting Notify dev services (Rust backend)..."
	@nohup sh -c 'cd backend_rust && DATABASE_URL="$${DATABASE_URL}" JWT_SECRET="$${JWT_SECRET:-dev-secret}" RUST_LOG="info" cargo run' > /tmp/notify-api.log 2>&1 &
	@nohup sh -c 'cd frontend && PORT="$${FRONTEND_PORT:-3000}" NEXT_PUBLIC_API_BASE="$${NEXT_PUBLIC_API_BASE:-http://localhost:4000}" npm run dev' > /tmp/notify-web.log 2>&1 &
	@echo "API log: /tmp/notify-api.log"
	@echo "Web log: /tmp/notify-web.log"

# Node.js backend (legacy)
dev-node:
	@echo "Starting Notify dev services (Node.js backend)..."
	@nohup sh -c 'cd backend && DATABASE_URL="$${DATABASE_URL}" JWT_SECRET="$${JWT_SECRET:-dev-secret}" PORT="$${PORT:-4000}" npm run dev' > /tmp/notify-api.log 2>&1 &
	@nohup sh -c 'cd backend && DATABASE_URL="$${DATABASE_URL}" JWT_SECRET="$${JWT_SECRET:-dev-secret}" npm run worker' > /tmp/notify-worker.log 2>&1 &
	@nohup sh -c 'cd frontend && PORT="$${FRONTEND_PORT:-3000}" NEXT_PUBLIC_API_BASE="$${NEXT_PUBLIC_API_BASE:-http://localhost:4000}" npm run dev' > /tmp/notify-web.log 2>&1 &
	@echo "API log: /tmp/notify-api.log"
	@echo "Worker log: /tmp/notify-worker.log"
	@echo "Web log: /tmp/notify-web.log"

stop:
	@echo "Stopping Notify dev services..."
	@pkill -f "target/debug/backend_rust" || true
	@pkill -f "tsx watch src/index.ts" || true
	@pkill -f "tsx src/worker.ts" || true
	@pkill -f "next dev" || true
	@echo "Stopped."

# SeaORM migrations (Rust)
migrate:
	@echo "Running SeaORM migration..."
	cd backend_rust && DATABASE_URL="$${DATABASE_URL}" cargo run --package migration -- up

migrate-down:
	@echo "Rolling back last migration..."
	cd backend_rust && DATABASE_URL="$${DATABASE_URL}" cargo run --package migration -- down

migrate-fresh:
	@echo "Resetting database and running all migrations..."
	cd backend_rust && DATABASE_URL="$${DATABASE_URL}" cargo run --package migration -- fresh

migrate-status:
	@echo "Checking migration status..."
	cd backend_rust && DATABASE_URL="$${DATABASE_URL}" cargo run --package migration -- status

# Prisma migrations (Node.js legacy)
migrate-prisma:
	@echo "Running Prisma migration (dev)..."
	cd backend && npx prisma migrate dev

migrate-prisma-deploy:
	@echo "Running Prisma migration (deploy)..."
	cd backend && npx prisma migrate deploy

db-push:
	@echo "Pushing schema to database..."
	cd backend && npx prisma db push

db-studio:
	@echo "Opening Prisma Studio..."
	cd backend && npx prisma studio

# Build
build:
	@echo "Building Rust backend..."
	cd backend_rust && cargo build --release

# Generate SeaORM entities from database
generate-entities:
	@echo "Generating SeaORM entities..."
	cd backend_rust && sea-orm-cli generate entity -o src/entity --with-serde both
