# Local Development Guide

Comprehensive guide for running and developing the project locally with real-time hot reload.

## System Requirements

- **Node.js**: >= 20.0.0
- **PNPM**: >= 8.0.0
- **Docker & Docker Compose**: Latest version
- **Git**: For cloning repository
- **Neon Account**: https://neon.tech (for database)

## Quick Start (Recommended)

1. **Clone Repository**:
   ```bash
   git clone <repository-url>
   cd Base
   ```

2. **Run Initialization Script**:
   ```bash
   ./scripts/setup/init-project.sh
   ```
   This script will install dependencies, generate clients, and setup environment files.

## Manual Setup


### 1. Clone Repository

```bash
git clone <repository-url>
cd Base
```

### 2. Install Dependencies

```bash
pnpm install
```

### 3. Setup Database (Neon)

Create environment configuration file:

```bash
cp deployments/local/env.local.example deployments/local/.env.local
```

Edit `.env.local` file and add your Neon DATABASE_URL:

```bash
# Get connection string from Neon Console: https://console.neon.tech
DATABASE_URL=postgresql://user:password@ep-xxx.region.neon.tech/dbname?sslmode=require&pgbouncer=true

# JWT Secrets (can keep defaults for dev)
JWT_SECRET=dev-jwt-secret-change-in-production
JWT_REFRESH_SECRET=dev-refresh-secret-change-in-production
```

**Note**: See [Neon Database Guide](neon-database.md) for detailed setup instructions.

### 4. Run Database Migrations

```bash
./scripts/db/migrate.sh iam-service dev
```

### 5. Seed Database (Optional)

```bash
./scripts/db/seed.sh iam-service
```

## Ways to Run the Project

### Method 1: Run All Services (Recommended)

Best for full-stack development or testing the entire system:

```bash
./scripts/dev/start-all.sh
```

This script will:
1. Check if Docker is running
2. Verify DATABASE_URL is configured
3. Start infrastructure (Redis, Traefik)
4. Start all services with hot reload

**Or run manually:**

```bash
# Step 1: Start infrastructure
cd deployments/local
docker-compose up -d
cd ../..

# Step 2: Start all services
pnpm dev
```

### Method 2: Run Specific Service

Best when working on a single service:

```bash
# Using script
./scripts/dev/start-service.sh iam-service

# Or run directly
cd services/iam-service
pnpm dev
```

### Method 3: Run Service Groups

```bash
# Run only backend services
pnpm --filter "./services/*" dev

# Run only frontend apps
pnpm --filter "./apps/*" dev

# Run specific service
pnpm --filter @goodgo/iam-service dev
```

### Method 4: Run With Docker Compose (Full Stack)

```bash
cd deployments/local
docker-compose up -d

# View logs
docker-compose logs -f

# Stop services
docker-compose down
```

## Access Points

When services are running, you can access:

| Service | URL | Description |
|---------|-----|-------------|
| **API Gateway** | http://localhost/api/v1 | Main entry point via Traefik |
| **IAM Service** | http://localhost:5001 | Direct IAM service access |
| **Auth API** | http://localhost/api/v1/auth | Auth API via gateway (backward compatible) |
| **Identity API** | http://localhost/api/v1/identity | Identity management API |
| **Access API** | http://localhost/api/v1/access | Access management API |
| **Governance API** | http://localhost/api/v1/governance | Governance API |
| **Web Admin** | http://admin.localhost or http://localhost:3000 | Admin dashboard |
| **Web Client** | http://localhost or http://localhost:3001 | Client web app |
| **Traefik Dashboard** | http://localhost:8080 | View routing and services |

## Hot Reload & Live Development

### Backend Services (TypeScript)

Backend services use `tsx watch` or `nodemon` for automatic restart on code changes:

```bash
# In services/iam-service/package.json
"scripts": {
  "dev": "tsx watch src/main.ts"
}
```

**When you change:**
- `.ts` files → Service auto-restarts (1-2 seconds)
- `.env` files → Manual restart required
- `prisma/schema.prisma` → Need to run migration

### Frontend Apps (Next.js)

Frontend apps use Next.js Fast Refresh:

```bash
# In apps/web-admin/package.json
"scripts": {
  "dev": "next dev"
}
```

**When you change:**
- React components → Updates instantly (no page reload)
- CSS/Tailwind → Updates instantly
- `next.config.js` → Restart required

### Shared Packages

When changing shared packages (in `packages/`):

```bash
# Packages auto-rebuild with Turbo watch mode
pnpm --filter @goodgo/logger dev
```

## Real-World Development Workflow

### Setup 3 Terminals

**Terminal 1: Run Services**
```bash
./scripts/dev/start-all.sh
# Or: pnpm dev
```

**Terminal 2: View Logs**
```bash
# View specific service logs
./scripts/dev/logs.sh iam-service

# Or view Docker logs
docker logs -f redis-cache-local
docker logs -f traefik-local
```

**Terminal 3: Development Tasks**
```bash
# Run tests
pnpm --filter @goodgo/iam-service test --watch

# Run migrations
./scripts/db/migrate.sh iam-service dev

# Format code
pnpm format
```

## Health Checks

### Health Endpoints

```bash
# Check API Gateway
curl http://localhost/api/v1/health

# Check Auth Service directly
curl http://localhost:5001/health

# Check Redis
docker exec redis-cache-local redis-cli ping
```

### Traefik Dashboard

Access http://localhost:8080 to view:
- All active routes
- Registered services
- Service health status

## Database Development

### Schema Changes

```bash
# 1. Edit prisma/schema.prisma
# 2. Create and apply migration
cd services/iam-service
pnpm prisma migrate dev --name add_new_field

# 3. Prisma Client auto-regenerates
```

### Reset Database (Development Only!)

```bash
cd services/iam-service
pnpm prisma migrate reset
```

### View Database

```bash
# Open Prisma Studio
cd services/iam-service
pnpm prisma studio
# Access: http://localhost:5555
```

## Debugging

### VS Code Debugging

Create `.vscode/launch.json`:

```json
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug Auth Service",
      "type": "node",
      "request": "launch",
      "runtimeExecutable": "pnpm",
      "runtimeArgs": ["--filter", "@goodgo/iam-service", "dev"],
      "skipFiles": ["<node_internals>/**"],
      "console": "integratedTerminal"
    }
  ]
}
```

### View Detailed Logs

```bash
# Service logs
./scripts/dev/logs.sh iam-service

# Docker logs
docker logs -f iam-service-local
docker logs -f redis-cache-local
docker logs -f traefik-local

# All logs
docker-compose -f deployments/local/docker-compose.yml logs -f
```

## Troubleshooting

### Port Already in Use

```bash
# Find process using port
lsof -i :5001  # Auth service
lsof -i :3000  # Web admin
lsof -i :6379  # Redis
lsof -i :80    # Traefik

# Kill process
kill -9 <PID>
```

### Docker Not Running

```bash
# Check Docker
docker info

# Start Docker Desktop (macOS)
open -a Docker

# Restart Docker services
docker-compose -f deployments/local/docker-compose.yml restart
```

### Database Connection Failed

```bash
# Check DATABASE_URL
cat deployments/local/.env.local | grep DATABASE_URL

# Test connection
cd services/iam-service
pnpm prisma db pull
```

### Module Not Found

```bash
# Cleanup and reinstall
./scripts/utils/cleanup.sh
pnpm install

# Or just cleanup node_modules
rm -rf node_modules
rm -rf services/*/node_modules
rm -rf apps/*/node_modules
rm -rf packages/*/node_modules
pnpm install
```

### Hot Reload Not Working

```bash
# Restart service
# Press Ctrl+C to stop, then:
pnpm dev

# Or restart Docker container
docker-compose -f deployments/local/docker-compose.yml restart iam-service
```

## Tips & Best Practices

### 1. Use Turbo Cache

Turbo cache speeds up builds:

```bash
# First run will be slow
pnpm dev

# Subsequent runs will be faster thanks to cache
# Cache stored in node_modules/.cache/turbo
```

### 2. Dev Selective Services

No need to run everything if working on one service:

```bash
# Run only iam-service
pnpm --filter @goodgo/iam-service dev

# Run iam-service with dependencies
pnpm --filter @goodgo/iam-service... dev
```

### 3. Watch Tests

```bash
# Run tests automatically on code changes
pnpm --filter @goodgo/iam-service test --watch
```

### 4. Auto-format Code

Install Prettier extension in VS Code and enable format on save.

### 5. Use Git Hooks

```bash
# Pre-commit hook will auto-format and lint
git commit -m "feat: add new feature"
```

## Environment Variables

### Development (.env.local)

```bash
# Database
DATABASE_URL=postgresql://user:pass@ep-xxx.neon.tech/db?sslmode=require&pgbouncer=true

# Redis
REDIS_HOST=redis
REDIS_PORT=6379

# JWT
JWT_SECRET=dev-jwt-secret
JWT_REFRESH_SECRET=dev-refresh-secret

# Service
NODE_ENV=development
LOG_LEVEL=debug
```

### Override for Specific Service

Create `.env.local` file in service directory:

```bash
# services/iam-service/.env.local
PORT=5001
LOG_LEVEL=debug
```

## Useful Commands

```bash
# Development
pnpm dev                    # Run all services
pnpm build                  # Build all
pnpm test                   # Test all
pnpm lint                   # Lint all
pnpm format                 # Format code

# Cleanup
pnpm clean                  # Remove build artifacts
./scripts/utils/cleanup.sh  # Full cleanup

# Database
./scripts/db/migrate.sh iam-service dev    # Migration
./scripts/db/seed.sh iam-service           # Seed data
./scripts/db/backup.sh iam-service         # Backup

# Docker
docker-compose -f deployments/local/docker-compose.yml up -d     # Start
docker-compose -f deployments/local/docker-compose.yml down      # Stop
docker-compose -f deployments/local/docker-compose.yml logs -f   # Logs
docker-compose -f deployments/local/docker-compose.yml restart   # Restart
```

## Additional Resources

- [Getting Started](getting-started.md) - Initial setup
- [Development Guide](development.md) - Development workflow
- [Neon Database Guide](neon-database.md) - Database guide
- [Troubleshooting](troubleshooting.md) - Problem solving
