# Neon Database Setup

This project uses [Neon PostgreSQL](https://neon.tech) for all environments (dev, staging, production).

## Why Neon?

- ✅ Serverless PostgreSQL with auto-scaling
- ✅ Branching support (dev, staging, production branches)
- ✅ Point-in-time restore
- ✅ Free tier for development
- ✅ Built-in connection pooling
- ✅ No infrastructure management needed

## Setup Instructions

### 1. Create Neon Project

1. Sign up at https://neon.tech
2. Create a new project: `goodgo-platform`
3. Note your connection string from the main branch

### 2. Create Branches

Create branches for each environment:

```bash
# Using Neon Console or CLI
# Main branch = development
# Create: staging branch
# Create: production branch
```

### 3. Get Connection Strings

For each branch, get the connection string:
- Format: `postgresql://user:password@ep-xxx.region.neon.tech/dbname?sslmode=require`
- Add `?pgbouncer=true` for connection pooling (recommended)

### 4. Configure Environment Variables

#### Local Development

Create `deployments/local/.env.local`:

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

#### Staging/Production

Store in GitHub Secrets:
- `NEON_DATABASE_URL_STAGING`
- `NEON_DATABASE_URL_PRODUCTION`

Or in Kubernetes Secrets (see `deployments/staging/kubernetes/secrets.yaml.example`)

## Connection Pooling

Neon provides built-in connection pooling. Add `?pgbouncer=true` to your connection string:

```
postgresql://user:pass@ep-xxx.region.neon.tech/dbname?sslmode=require&pgbouncer=true
```

## Migration

### Development

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

### Staging/Production

Migrations run automatically in CI/CD workflows before deployment.

## Backup & Restore

Neon provides automatic backups and point-in-time restore via their console.

For manual backup:

```bash
# Using pg_dump
pg_dump $DATABASE_URL > backup.sql

# Restore
psql $DATABASE_URL < backup.sql
```

## Monitoring

Monitor your databases via Neon Console:
- Connection metrics
- Query performance
- Storage usage
- Branch status

## Cost Optimization

- **Free tier**: Sufficient for development
- **Staging**: Use free tier or minimal paid plan
- **Production**: Scale based on usage

## Troubleshooting

### Connection Issues

1. Check connection string format
2. Verify SSL mode: `?sslmode=require`
3. Check IP allowlist in Neon console (if enabled)
4. Verify credentials

### Migration Issues

1. Ensure DATABASE_URL is set correctly
2. Check Prisma schema matches database
3. Review migration files

### Performance Issues

1. Enable connection pooling: `?pgbouncer=true`
2. Check query performance in Neon console
3. Review indexes in Prisma schema
