# justfile for Euchre Camp
# Automates development, testing, and deployment tasks.
# Designed for CI/CD pipelines and local development.

# --- Configuration ---
set dotenv-load
set positional-arguments

# Project name
PROJECT := "euchre-camp"

# Docker registry
REGISTRY := "docker.notsosm.art"
IMAGE_TAG := "latest"

# Get git commit hash (short version)
GIT_COMMIT := `git rev-parse --short HEAD`

# Image tag with git commit (use same format as GIT_COMMIT)
IMAGE_TAG_COMMIT := `git rev-parse --short HEAD`

# --- Variables ---
# Database
DB_CONTAINER := "euchre-camp-postgres"
DATABASE_PROVIDER := env_var_or_default("DATABASE_PROVIDER", "sqlite")
DATABASE_URL := env_var_or_default("DATABASE_URL", "file:./prisma/dev.db")

# --- Setup & Installation ---

# Install dependencies and setup environment
setup:
    @echo "Installing dependencies..."
    npm install
    @echo "Setting up database..."
    npm run db:setup-postgres
    @echo "Generating Prisma client..."
    npx prisma generate

# --- Development ---

# Start the development server
dev:
    npm run dev

# Lint the codebase
lint:
    npm run lint

# Type check the codebase
typecheck:
    npx tsc --noEmit

# Format code (if prettier is available, otherwise just lint)
format:
    npx prettier --write .

# --- Testing ---

# Run all tests (unit + acceptance with SQLite)
# Note: Uses Docker containers for consistent environment
test: test-unit test-acceptance-sqlite

# Run all tests with PostgreSQL (Docker)
test-pg: test-unit test-acceptance-postgres

# Run unit tests (Vitest)
test-unit:
    npm run test:run

# Run acceptance tests with SQLite (fast, no Docker needed)
test-acceptance-sqlite:
    @echo "Running acceptance tests with SQLite..."
    DATABASE_PROVIDER=sqlite DATABASE_URL=file:./prisma/ci.db BETTER_AUTH_SECRET=test-secret-key npm run test:acceptance

# Run acceptance tests with PostgreSQL (Docker)
test-acceptance-postgres:
    @echo "Starting Docker containers for acceptance tests..."
    docker compose up -d
    @echo "Waiting for services to be ready..."
    sleep 10
    @echo "Running acceptance tests..."
    npm run test:acceptance
    @echo "Stopping Docker containers..."
    docker compose down

# Run Cucumber e2e tests with SQLite
test-cucumber-sqlite:
    @echo "Running Cucumber e2e tests with SQLite..."
    DATABASE_PROVIDER=sqlite DATABASE_URL=file:./prisma/ci.db npm run test:acceptance:cucumber

# Run Cucumber e2e tests with PostgreSQL (uses .env.development)
test-cucumber-postgres:
    @echo "Running Cucumber e2e tests with PostgreSQL..."
    npm run test:acceptance:cucumber

# Run Cucumber e2e tests with PostgreSQL against production build
# This is more reliable than dev server (no HMR, faster API responses)
test-cucumber-postgres-prod:
    @echo "Building application for production..."
    bun run build
    @echo "Starting production server in background..."
    bun run start > /tmp/next-prod.log 2>&1 &
    SERVER_PID=$$!
    @echo "Waiting for server to be ready..."
    sleep 15
    @echo "Running Cucumber e2e tests against production build..."
    npm run test:acceptance:cucumber || true
    @echo "Stopping production server..."
    kill $$SERVER_PID 2>/dev/null || true
    @echo "Tests completed."

# Run all e2e tests (both Playwright and Cucumber)
test-e2e: test-acceptance-sqlite test-cucumber-sqlite

# Run database migrations (Prisma)
migrate:
    npx prisma migrate dev

# Seed the database
seed:
    npm run db:seed

# Switch database provider
db-switch-sqlite:
    npm run db:switch sqlite

db-switch-postgres:
    npm run db:switch postgresql

# --- Docker ---

# Build the Docker image (standard build)
docker-build:
    @echo "Building Docker image {{PROJECT}}:{{IMAGE_TAG}}..."
    docker build --build-arg GIT_COMMIT={{GIT_COMMIT}} -t {{PROJECT}}:{{IMAGE_TAG}} .

docker-build-commit:
    @echo "Building Docker image {{PROJECT}}:{{IMAGE_TAG_COMMIT}}..."
    docker build --build-arg GIT_COMMIT={{GIT_COMMIT}} -t {{PROJECT}}:{{IMAGE_TAG_COMMIT}} .

# Build and tag with both latest and commit hash
docker-build-full: docker-build docker-build-commit

# Fast rebuild using Docker BuildKit cache
# Uses build cache to speed up rebuilds when only code changes
docker-rebuild-fast:
    @echo "Fast rebuilding Docker image {{PROJECT}}:{{IMAGE_TAG}}..."
    DOCKER_BUILDKIT=1 docker build \
        --build-arg GIT_COMMIT={{GIT_COMMIT}} \
        --cache-from={{PROJECT}}:{{IMAGE_TAG}} \
        -t {{PROJECT}}:{{IMAGE_TAG}} \
        -t {{PROJECT}}:{{IMAGE_TAG_COMMIT}} \
        .

# Run the Docker container locally
docker-run: docker-build
    @echo "Running Docker container {{PROJECT}}..."
    docker run -d -p 3000:3000 --name {{PROJECT}} {{PROJECT}}:{{IMAGE_TAG}}

# Stop and remove the Docker container
docker-stop:
    @echo "Stopping Docker container {{PROJECT}}..."
    docker stop {{PROJECT}} || true
    docker rm {{PROJECT}} || true

# Clean up Docker images and containers
docker-clean: docker-stop
    @echo "Removing Docker image {{PROJECT}}:{{IMAGE_TAG}}..."
    docker rmi {{PROJECT}}:{{IMAGE_TAG}} || true

# --- Deployment ---

# Tag image for registry
docker-tag:
    @echo "Tagging image for registry..."
    docker tag {{PROJECT}}:{{IMAGE_TAG}} {{REGISTRY}}/{{PROJECT}}:{{IMAGE_TAG}} || true
    docker tag {{PROJECT}}:{{IMAGE_TAG_COMMIT}} {{REGISTRY}}/{{PROJECT}}:{{IMAGE_TAG_COMMIT}} || true
    @echo "Tagged {{PROJECT}}:{{IMAGE_TAG}} -> {{REGISTRY}}/{{PROJECT}}:{{IMAGE_TAG}}"
    @echo "Tagged {{PROJECT}}:{{IMAGE_TAG_COMMIT}} -> {{REGISTRY}}/{{PROJECT}}:{{IMAGE_TAG_COMMIT}}"

# Push image to registry (builds, tags, and pushes)
docker-push: docker-build-full
    @echo "Tagging images for registry..."
    docker tag {{PROJECT}}:{{IMAGE_TAG}} {{REGISTRY}}/{{PROJECT}}:{{IMAGE_TAG}} || true
    docker tag {{PROJECT}}:{{IMAGE_TAG_COMMIT}} {{REGISTRY}}/{{PROJECT}}:{{IMAGE_TAG_COMMIT}} || true
    @echo "Pushing images to {{REGISTRY}}..."
    docker push {{REGISTRY}}/{{PROJECT}}:{{IMAGE_TAG}}
    docker push {{REGISTRY}}/{{PROJECT}}:{{IMAGE_TAG_COMMIT}}

# --- CI/CD Pipeline Simulation ---

# Run full CI pipeline locally (lint, test, build, push)
# Matches the Gitea Actions workflow
ci: lint typecheck test-unit test-acceptance-sqlite docker-build
    @echo "CI Pipeline completed successfully!"

# PR validation (what runs on pull requests)
pr-validate: lint typecheck test-unit test-acceptance-sqlite
    @echo "PR validation completed successfully!"

# Run CI with PostgreSQL (for release workflow simulation)
ci-postgres: lint typecheck test-unit test-acceptance-postgres docker-build
    @echo "CI Pipeline with PostgreSQL completed successfully!"

# --- Utilities ---

# Show help information
help:
    @just --list

# Clean up project (remove node_modules, build artifacts)
clean:
    @echo "Cleaning project..."
    rm -rf node_modules .next dist

# Generate Prisma client
prisma-generate:
    npx prisma generate

# Reset development database
db-reset-dev:
    npm run db:reset-dev

# Setup development database
db-setup-dev:
    npm run db:setup-dev

# Clean production database (remove test records)
db-clean-prod:
    npm run db:cleanup-prod

# Check production database for test records
db-check-prod:
    npm run db:check-prod

# Create admin user
admin-create:
    node scripts/create-admin-via-api.js

# List all users
users-list:
    node scripts/list-users.js

# Update admin password
admin-update-password:
    node scripts/update-admin-password.js

# Bump version
version-bump-patch:
    npm run version:patch

version-bump-minor:
    npm run version:minor

version-bump-major:
    npm run version:major

# Docker Compose shortcuts
docker-up:
    npm run docker:up

docker-down:
    npm run docker:down

docker-logs:
    npm run docker:logs

# View workflow status
workflow-status:
    @echo "Current workflows in .gitea/workflows/:"
    ls -la .gitea/workflows/
    @echo ""
    @echo "PR Workflow: Runs unit + acceptance tests on pull requests"
    @echo "Test Workflow: Runs unit tests on all branch pushes"
    @echo "Release Workflow: Runs on main branch pushes (version bump + Docker build)"
    @echo ""
    @echo "Note: CI image approach deprecated due to Gitea Actions workspace mounting"

# Check current database provider
db-status:
    @echo "Database Provider: ${DATABASE_PROVIDER}"
    @echo "Database URL: ${DATABASE_URL}"
    @echo ""
    @echo "Current schema.prisma provider:"
    grep -A 2 "datasource db" prisma/schema.prisma | head -3
