# GPSF-MIS Docker Setup Guide

This document explains how to run the entire GPSF-MIS application (backend + frontend + database) using Docker.

## 🚀 Quick Start

### Prerequisites

- Docker Desktop installed and running
- Docker Compose v2.x or higher

### First Time Setup

1. **Clone the repository** (if not already done)

   ```bash
   cd /Users/rattanakung/Dev/GPSF-MIS
   ```

2. **Configure environment variables**

   The `.env` file is already created with default values. Review and update if needed:

   ```bash
   # Edit .env file if you need to change database credentials or other settings
   nano .env
   ```

3. **Start all services with one command**

   ```bash
   docker-compose up -d
   ```

   This single command will:
   - ✅ Start PostgreSQL database
   - ✅ Wait for database to be healthy
   - ✅ Build and start the backend
   - ✅ Run Prisma migrations automatically
   - ✅ Seed the database (if `SEED_DATABASE=true`)
   - ✅ Build and start the frontend
   - ✅ Connect all services in a network

4. **Access the application**
   - Frontend: http://localhost:3001
   - Backend API: http://localhost:3002
   - Prisma Studio: http://localhost:5555
   - Backend Health: http://localhost:3002/api/v1/health

5. **Default Admin Credentials** (after seeding)
   - Email: `admin@gmail.com`
   - Password: `12345678`

## 📋 Available Commands

### Start all services

```bash
docker-compose up -d
```

### Stop all services

```bash
docker-compose down
```

### Stop and remove all data (including database)

```bash
docker-compose down -v
```

### View logs

```bash
# All services
docker-compose logs -f

# Specific service
docker-compose logs -f backend
docker-compose logs -f frontend
docker-compose logs -f postgres
```

### Rebuild services after code changes

```bash
# Rebuild all
docker-compose up -d --build

# Rebuild specific service
docker-compose up -d --build backend
docker-compose up -d --build frontend
```

### Restart a specific service

```bash
docker-compose restart backend
docker-compose restart frontend
```

### Access service shell

```bash
# Backend container
docker exec -it gpsf-mis-backend sh

# Frontend container
docker exec -it gpsf-mis-frontend sh

# Database container
docker exec -it gpsf-mis-postgres psql -U khonvakhim -d GPSF_MIS_DB
```

## 🗄️ Database Management

### Run migrations manually

```bash
docker exec -it gpsf-mis-backend npx prisma migrate deploy
```

### Seed database manually

```bash
docker exec -it gpsf-mis-backend npm run prisma:seed
```

### Access Prisma Studio (Database GUI)

Prisma Studio runs automatically with `docker-compose up -d` and is accessible at:

**http://localhost:5555**

Or use the shortcut:

```bash
make studio
```

This will open Prisma Studio in your browser.

### Reset database (⚠️ Warning: Deletes all data)

```bash
docker-compose down -v
docker-compose up -d
```

## 🏗️ Architecture

The Docker setup consists of three main services:

```
┌─────────────────────────────────────────┐
│           Docker Network                │
│         (gpsf-network)                  │
│                                         │
│  ┌──────────┐  ┌──────────┐  ┌────────┐│
│  │PostgreSQL│  │ Backend  │  │Frontend││
│  │  :5432   │◄─┤  :3002   │◄─┤ :3001  ││
│  └──────────┘  └──────────┘  └────────┘│
│                                         │
└─────────────────────────────────────────┘
         ▲                ▲          ▲
         │                │          │
    DB Volume        Uploads Vol   (none)
```

### Service Dependencies

- **Frontend** depends on **Backend** (waits for health check)
- **Backend** depends on **PostgreSQL** (waits for health check)
- **PostgreSQL** starts first

### Volumes

- `postgres_data`: Persists database data
- `uploads_data`: Persists uploaded files (avatars, documents, etc.)

## ⚙️ Environment Variables

Key environment variables in `.env`:

| Variable              | Description          | Default                      |
| --------------------- | -------------------- | ---------------------------- |
| `DB_USERNAME`         | PostgreSQL username  | khonvakhim                   |
| `DB_PASSWORD`         | PostgreSQL password  | 1234                         |
| `DB_NAME`             | Database name        | GPSF_MIS_DB                  |
| `DB_PORT`             | Database port (host) | 5432                         |
| `PORT`                | Backend API port     | 3002                         |
| `JWT_SECRET`          | JWT signing secret   | (change in production)       |
| `SEED_DATABASE`       | Auto-seed on startup | true                         |
| `SEED_ADMIN_EMAIL`    | Admin user email     | admin@gmail.com              |
| `SEED_ADMIN_PASSWORD` | Admin user password  | 12345678                     |
| `NEXT_PUBLIC_API_URL` | Frontend API URL     | http://localhost:3002/api/v1 |

## 🔧 Troubleshooting

### Services won't start

```bash
# Check service status
docker-compose ps

# View logs for errors
docker-compose logs -f
```

### Database connection errors

```bash
# Ensure postgres is healthy
docker-compose ps postgres

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

### Port already in use

```bash
# Change ports in .env file
DB_PORT=5433
PORT=3007

# Or stop conflicting services
docker ps
docker stop <container-id>
```

### Reset everything and start fresh

```bash
# Stop all services and remove volumes
docker-compose down -v

# Remove any orphaned containers
docker system prune -a

# Start again
docker-compose up -d
```

### Migrations not running

```bash
# Check backend logs
docker-compose logs backend

# Run migrations manually
docker exec -it gpsf-mis-backend npx prisma migrate deploy
```

### Frontend can't connect to backend

- Ensure `NEXT_PUBLIC_API_URL` in `.env` points to the correct backend URL
- For Docker internal communication, backend uses service name `backend`
- For browser access, use `http://localhost:3002`

## 📁 Project Structure

```
GPSF-MIS/
├── docker-compose.yml       # Main Docker Compose configuration
├── .env                      # Environment variables
├── .env.example             # Example environment file
├── backend/
│   ├── Dockerfile           # Backend Docker image
│   ├── docker-entrypoint.sh # Migration & seeding script
│   └── ...
└── frontend/
    ├── Dockerfile           # Frontend Docker image
    └── ...
```

## 🔒 Production Notes

For production deployment:

1. **Change sensitive values in `.env`:**
   - Use strong `DB_PASSWORD`
   - Use a secure random `JWT_SECRET`
   - Use real email credentials
   - Set `SEED_DATABASE=false` after initial setup

2. **Use production docker-compose:**
   - Consider using `backend/docker-compose.prod.yml` as reference
   - Add proper SSL/TLS termination
   - Use environment-specific configurations

3. **Database backups:**

   ```bash
   docker exec gpsf-mis-postgres pg_dump -U khonvakhim GPSF_MIS_DB > backup.sql
   ```

4. **Update images regularly:**
   ```bash
   docker-compose pull
   docker-compose up -d --build
   ```

## 📞 Support

For issues or questions:

- Check logs: `docker-compose logs -f`
- Review environment variables in `.env`
- Ensure Docker Desktop is running
- Check port availability (3001, 3002, 5432)
