# Estate Platform - Complete Setup Guide

## Table of Contents
1. [Quick Start](#quick-start)
2. [Prerequisites](#prerequisites)
3. [Local Development Setup](#local-development-setup)
4. [Docker Setup](#docker-setup)
5. [Redis Configuration](#redis-configuration)
6. [Database Setup](#database-setup)
7. [Authentication Setup](#authentication-setup)
8. [Testing the Application](#testing-the-application)
9. [Troubleshooting](#troubleshooting)

---

## Quick Start

### Using Docker (Recommended)

```bash
# 1. Clone the repository
git clone <repo-url>
cd estate-platform

# 2. Copy environment file
cp .env.example .env.local

# 3. Start all services (includes Redis)
docker-compose up -d

# 4. Run database migrations
docker-compose exec web npm run db:migrate

# 5. Seed the database (optional)
docker-compose exec web npm run db:seed

# 6. Access the application
open http://localhost:3000
```

### Local Development

```bash
# 1. Install dependencies
npm install

# 2. Start Redis locally (macOS)
redis-server

# 3. Setup database
npm run db:migrate
npm run db:seed

# 4. Run development server
npm run dev

# 5. Open browser
open http://localhost:3001
```

---

## Prerequisites

### Required
- Node.js 18+ ([Download](https://nodejs.org/))
- PostgreSQL 12+ ([Download](https://www.postgresql.org/download/))
- Redis 6+ ([Download](https://redis.io/download))

### Optional (for Docker)
- Docker ([Download](https://www.docker.com/products/docker-desktop))
- Docker Compose (included with Docker Desktop)

### For OAuth Providers (optional)
- Google OAuth credentials
- GitHub OAuth credentials
- Facebook OAuth credentials
- Discord OAuth credentials

---

## Local Development Setup

### 1. Install Node.js

```bash
# Verify installation
node --version  # Should be v18+
npm --version   # Should be v9+
```

### 2. Clone Repository

```bash
git clone <repo-url>
cd estate-platform
```

### 3. Install Dependencies

```bash
npm install
```

### 4. Configure Environment Variables

```bash
# Copy example environment file
cp .env.example .env.local

# Edit with your values
nano .env.local  # or use your preferred editor
```

**Important variables to set:**
```bash
DATABASE_URL="postgresql://postgres:postgres@localhost:5432/estate_platform"
REDIS_URL="redis://localhost:6379"
APP_BASE_URL="http://localhost:3001"
BETTER_AUTH_SECRET="your-random-secret-key"
```

### 5. Setup PostgreSQL Database

```bash
# Create database (if not exists)
createdb estate_platform

# Run migrations
npm run db:migrate

# Optional: Seed with sample data
npm run db:seed
```

### 6. Start Redis

```bash
# macOS (using Homebrew)
redis-server

# Linux (systemd)
sudo systemctl start redis-server

# Verify Redis is running
redis-cli ping  # Should output "PONG"
```

### 7. Start Development Server

```bash
npm run dev

# Server runs at http://localhost:3001
```

### 8. Verify Setup

Open your browser and navigate to:
- **Frontend**: http://localhost:3001
- **Admin Setup**: http://localhost:3001/admin/setup
- **API Health**: http://localhost:3001/api/health (if available)

---

## Docker Setup

### 1. Install Docker

```bash
# macOS
brew install docker

# Linux (Ubuntu)
sudo apt-get install docker.io docker-compose

# Verify installation
docker --version
docker-compose --version
```

### 2. Configure Environment

```bash
# Copy and edit environment
cp .env.example .env.local

# For Docker, use:
REDIS_URL="redis://:redis_password@redis:6379"
DATABASE_URL="postgresql://postgres:postgres@postgres:5432/estate_platform"
```

### 3. Start Services

```bash
# Start all services in background
docker-compose up -d

# View logs
docker-compose logs -f

# View specific service logs
docker-compose logs -f web    # Next.js app
docker-compose logs -f redis  # Redis
docker-compose logs -f postgres  # Database
```

### 4. Initialize Database

```bash
# Run migrations inside Docker
docker-compose exec web npm run db:migrate

# Seed with sample data
docker-compose exec web npm run db:seed
```

### 5. Access Application

- **Frontend**: http://localhost:3000
- **Admin Setup**: http://localhost:3000/admin/setup

### 6. Stop Services

```bash
# Stop containers
docker-compose down

# Stop and remove volumes (WARNING: deletes data!)
docker-compose down -v
```

---

## Redis Configuration

### Docker Setup (Recommended)

Redis is automatically configured in `docker-compose.yml`:

```yaml
redis:
  image: redis:7-alpine
  ports:
    - "6379:6379"
  environment:
    REDIS_PASSWORD: redis_password
  volumes:
    - redis_data:/data
```

### Local Redis Setup

#### macOS

```bash
# Install with Homebrew
brew install redis

# Start Redis
redis-server

# Start as service (starts on boot)
brew services start redis

# Stop service
brew services stop redis

# Verify connection
redis-cli ping  # Should output "PONG"
```

#### Linux (Ubuntu/Debian)

```bash
# Install Redis
sudo apt-get update
sudo apt-get install redis-server

# Start service
sudo systemctl start redis-server

# Enable on boot
sudo systemctl enable redis-server

# Check status
sudo systemctl status redis-server

# Verify connection
redis-cli ping  # Should output "PONG"
```

#### Windows

```bash
# Using Windows Subsystem for Linux (WSL2)
# OR use Docker for Windows
docker run -d -p 6379:6379 redis:7-alpine
```

### Verify Redis Connection

```bash
# Connect to Redis CLI
redis-cli

# Test commands
ping              # Returns "PONG"
set key value     # Set a key
get key           # Get the value
del key           # Delete the key
FLUSHALL          # Clear all data (be careful!)
exit              # Exit CLI
```

### Configure Environment Variables

In `.env.local`:

```bash
# Local development
REDIS_URL="redis://localhost:6379"

# Docker setup
REDIS_URL="redis://:redis_password@redis:6379"

# With password (production)
REDIS_URL="redis://:your_strong_password@localhost:6379"
```

---

## Database Setup

### Using Docker (Easiest)

```bash
# Database runs automatically with docker-compose
docker-compose up -d postgres

# Run migrations
docker-compose exec web npm run db:migrate

# Seed data
docker-compose exec web npm run db:seed

# Access database
docker-compose exec postgres psql -U postgres -d estate_platform
```

### Local PostgreSQL Setup

#### macOS

```bash
# Install PostgreSQL
brew install postgresql@15

# Start PostgreSQL
brew services start postgresql@15

# Verify installation
psql --version
```

#### Linux (Ubuntu/Debian)

```bash
# Install PostgreSQL
sudo apt-get update
sudo apt-get install postgresql postgresql-contrib

# Start service
sudo systemctl start postgresql

# Verify
psql --version
```

### Create Database

```bash
# Connect to PostgreSQL
psql -U postgres

# Create database
CREATE DATABASE estate_platform;

# Exit
\q
```

### Run Migrations

```bash
# Generate Prisma client
npm run db:generate

# Run migrations
npm run db:migrate

# Seed database (optional)
npm run db:seed
```

### Database Commands

```bash
# Generate Prisma client after schema changes
npm run db:migrate

# Create new migration (if using manual SQL)
npm run db:migrate

# Reset database (WARNING: deletes all data!)
npx prisma migrate reset

# View database
npx prisma studio
```

---

## Authentication Setup

### BetterAuth Configuration

BetterAuth is configured in `lib/auth.ts`. Sessions are automatically cached with Redis.

### Add OAuth Providers

1. **Navigate to Admin Setup**
   - URL: `http://localhost:3001/admin/setup`
   - Login as admin user

2. **Configure OAuth Providers**
   - Click each provider (Google, GitHub, Facebook, Discord)
   - Add Client ID and Client Secret
   - Save configuration

3. **Get Provider Credentials**

#### Google OAuth

1. Go to [Google Cloud Console](https://console.cloud.google.com/)
2. Create new project
3. Enable Google+ API
4. Create OAuth 2.0 credentials (Web application)
5. Add authorized redirect URIs:
   - `http://localhost:3001/auth/google/callback`
   - `https://yourdomain.com/auth/google/callback`
6. Copy Client ID and Client Secret to admin setup

#### GitHub OAuth

1. Go to [GitHub Settings](https://github.com/settings/developers)
2. Click "New OAuth App"
3. Fill in application details:
   - **Authorization callback URL**: `http://localhost:3001/auth/github/callback`
4. Copy Client ID and Client Secret

#### Facebook OAuth

1. Go to [Facebook Developers](https://developers.facebook.com/)
2. Create new app
3. Add Facebook Login product
4. Set Valid OAuth Redirect URIs:
   - `http://localhost:3001/auth/facebook/callback`
5. Copy App ID and App Secret

#### Discord OAuth

1. Go to [Discord Developer Portal](https://discord.com/developers/applications)
2. Create new application
3. Go to OAuth2 settings
4. Add redirect URI:
   - `http://localhost:3001/auth/discord/callback`
5. Copy Client ID and Client Secret

### Session Management

Sessions are automatically cached with Redis:
- **Cache duration**: 7 days
- **Auto-expiry**: TTL automatically managed
- **User data cache**: 1 hour (reduces database queries)

---

## Testing the Application

### Test User Creation

1. Go to `/signup`
2. Fill in user details:
   - First Name: "John"
   - Last Name: "Doe"
   - Email: "john@example.com"
   - Password: "SecurePassword123"
3. Click Sign Up

### Test OAuth Login

1. Go to `/signin`
2. Click any OAuth provider button
3. Authenticate with provider credentials
4. Should redirect to dashboard

### Test Admin Setup

1. Login as admin
2. Navigate to `/admin/setup`
3. Configure OAuth providers
4. Save settings (cached with Redis)
5. Verify settings persist

### Test Redis Caching

```bash
# Connect to Redis
redis-cli

# Monitor cache operations
MONITOR

# In another terminal, make API calls
curl http://localhost:3001/api/admin/setup

# You should see Redis commands in monitor
```

### Test Database

```bash
# View Prisma studio
npm run db:studio

# Or connect directly
psql -U postgres -d estate_platform

# Query users
SELECT * FROM "User";

# Query sessions
SELECT * FROM "Session";
```

---

## Troubleshooting

### Redis Connection Issues

**Error**: `Error: connect ECONNREFUSED 127.0.0.1:6379`

**Solution**:
```bash
# Check if Redis is running
redis-cli ping

# Start Redis
redis-server

# Or check Docker
docker-compose logs redis
docker-compose restart redis
```

### Database Connection Issues

**Error**: `Error: connect ECONNREFUSED localhost:5432`

**Solution**:
```bash
# Check PostgreSQL status
psql -U postgres -c "SELECT version();"

# Start PostgreSQL
brew services start postgresql@15  # macOS
sudo systemctl start postgresql     # Linux

# Check Docker
docker-compose logs postgres
docker-compose restart postgres
```

### Port Already in Use

**Error**: `Port 3001 is already in use`

**Solution**:
```bash
# Kill process using port
lsof -i :3001
kill -9 <PID>

# Or use different port
npm run dev -- -p 3002
```

### Authentication Issues

**Issue**: Cannot login or OAuth not working

**Solution**:
1. Check OAuth credentials in admin setup
2. Verify OAuth callback URLs match provider settings
3. Check browser cookies: `Settings > Cookies > estate-platform`
4. Clear cache: `Ctrl+Shift+Delete` (Chrome)
5. Check console for errors: `F12 > Console`

### Admin Setup Page Blank

**Issue**: `/admin/setup` page shows nothing

**Solution**:
1. Ensure logged in as admin
2. Check Redis connection: `redis-cli ping`
3. Check API response: `curl http://localhost:3001/api/admin/setup`
4. Check browser console for errors
5. Restart application

### Slow Performance

**Issue**: Application feels slow

**Solution**:
1. **Check Redis**:
   ```bash
   redis-cli
   INFO stats
   ```

2. **Check Database**:
   - Monitor slow queries
   - Check indexes are created

3. **Check Resources**:
   ```bash
   # Docker
   docker stats
   
   # Local
   top  # macOS/Linux
   ```

4. **Clear Cache**:
   ```bash
   redis-cli FLUSHALL  # WARNING: clears all cache!
   ```

### Can't Access Admin Setup

**Issue**: `/admin/setup` returns 401 Unauthorized

**Solution**:
1. Check user role is "ADMIN" in database
2. Verify session/auth token exists
3. Check JWT secret in `.env.local`
4. Login again to refresh session

### Docker Issues

**Stop all containers**:
```bash
docker-compose down
```

**Remove all data** (fresh start):
```bash
docker-compose down -v
```

**Rebuild containers**:
```bash
docker-compose up -d --build
```

**View logs**:
```bash
docker-compose logs -f [service]  # web, redis, postgres
```

---

## Performance Optimization Tips

1. **Enable Redis Caching**
   - All API responses are automatically cached
   - Reduces database queries by 50-70%

2. **Optimize Database Indexes**
   - Check `prisma/schema.prisma` for @@index
   - Add indexes for frequently queried fields

3. **Use CDN for Static Assets**
   - Configure Cloudflare or similar
   - Serve images and CSS globally

4. **Monitor with Tools**
   - Use `npm run db:studio` for queries
   - Use `redis-cli MONITOR` for cache hits
   - Use browser DevTools for performance

5. **Enable Compression**
   - Gzip enabled by default in Next.js
   - Verify with: `curl -I http://localhost:3001 | grep encoding`

---

## Next Steps

1. Configure OAuth providers for your environment
2. Setup email service for notifications
3. Configure Stripe for payments (if needed)
4. Deploy to production environment
5. Setup monitoring and logging
6. Configure backups for database and Redis

---

## Support & Resources

- [Next.js Documentation](https://nextjs.org/docs)
- [BetterAuth Documentation](https://better-auth.com)
- [Prisma Documentation](https://www.prisma.io/docs)
- [Redis Documentation](https://redis.io/documentation)
- [PostgreSQL Documentation](https://www.postgresql.org/docs)

For issues, check the [REDIS_SETUP.md](./REDIS_SETUP.md) for additional Redis-specific guidance.
