# Magasinet KBH - Development Guide

This guide contains all the necessary instructions to run the Magasinet KBH project locally using Docker and pnpm.

## 🚀 Quick Start

### Prerequisites

- **Docker** (with Docker Compose)
- **Node.js** (v20 or newer)
- **pnpm**

### 1. Initial Setup

```bash
# Clone the repository and navigate to the project root
cd magasinetkbh

# Install dependencies
pnpm install

# Setup environment variables (copies .env.example to .env if it doesn't exist)
make
```

### 2. Running the Project

You can choose one of two ways to run the project:

#### Option A: Full Docker (Recommended for testing)
This option runs the application and all necessary services (DB, MinIO, Mailpit) in containers.

```bash
# Start everything
make up

# Run a command (e.g., migrations) inside the container
make pnpm db:migrate
```

#### Option B: Hybrid Mode (Docker Services + Local App - Recommended for development)
This option runs only the supporting services in Docker, while the application itself runs locally. This is best for active development as it provides faster hot-reloading.

```bash
# Start only the services (DB, MinIO, Mailpit)
make up-db up-minio up-mailpit

# Run the application locally
pnpm dev
```

### 3. Accessing Services

- **Application**: http://localhost:3000
- **Email (Mailpit)**: http://localhost:8025
- **Storage (MinIO Console)**: http://localhost:9001
- **Database (PostgreSQL)**: localhost:5432

## 📋 Available Commands (Makefile)

### Infrastructure Management

| Command            | Description                                                  |
|--------------------|--------------------------------------------------------------|
| `make up`          | Start all services                                           |
| `make down`        | Stop all services                                            |
| `make up-db`       | Start only the database                                      |
| `make up-minio`    | Start only MinIO                                             |
| `make up-mailpit`  | Start only Mailpit                                           |
| `make restart`     | Restart the project                                          |
| `make pnpm <args>` | Run pnpm command in container (e.g., `make pnpm db:migrate`) |

### Database Management

| In docker               | Command            | Description                      |
|-------------------------|--------------------|----------------------------------|
| `make pnpm db:generate` | `pnpm db:generate` | Generate migrations              |
| `make pnpm db:migrate`  | `pnpm db:migrate`  | Run migrations                   |
| `make pnpm db:seed`     | `pnpm db:seed`     | Seed the database with test data |
| `make pnpm db:studio`   | `pnpm db:studio`   | Open Drizzle Studio              |

### Migration Modes

The project uses versioned database migrations for all environments:

- **Migration System**: Uses `drizzle-kit migrate` for versioned migrations across all environments
- **Automatic Migrations**: Migrations run automatically when starting Docker containers
- **Production Ready**: Consistent migration approach for development and production

See [Migration Documentation](docs/MIGRATIONS.md) for details.

### Development Scripts

| Script  | Command      | Description                      |
|---------|--------------|----------------------------------|
| `dev`   | `next dev`   | Start Next.js development server |
| `build` | `next build` | Build for production             |
| `start` | `next start` | Start production server          |

## 🐳 Docker Services

### Service Architecture

```
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   Next.js App   │    │   PostgreSQL    │    │     MinIO       │
│   Port: 3000    │    │   Port: 5432    │    │  Port: 9000/9001│
└─────────────────┘    └─────────────────┘    └─────────────────┘
         │                       │                       │
         └───────────────────────┼───────────────────────┘
                                 │
                    ┌─────────────────┐
                    │    Mailpit      │
                    │ Port: 8025/1025 │
                    └─────────────────┘
```

### Service Details

#### **PostgreSQL Database**
- **Image**: `postgres:16-alpine`
- **Port**: 5432
- **Database**: `magasinetkbh`
- **User**: `postgres`
- **Password**: `postgres_password`

#### **Next.js Application**
- **Port**: 3000 (main), 9229 (debug)
- **Environment**: Development mode with hot reloading
- **Volumes**: Source code mounted for live updates

#### **MinIO (S3-Compatible Storage)**
- **API Port**: 9000
- **Console Port**: 9001
- **Access Key**: `minioadmin`
- **Secret Key**: `minioadmin123`
- **Bucket**: `magasinetkbh-uploads` (auto-created)

#### **Mailpit (Email Testing)**
- **Web Interface**: 8025
- **SMTP Port**: 1025
- **Features**: Email capture, testing, debugging

## 🔧 Configuration

### Environment Variables

Ensure you have a `.env` file in the root directory. You can use `.env.example` as a template.

```bash
# Database Configuration
DATABASE_URL=postgresql://postgres:postgres_password@localhost:5432/magasinetkbh
POSTGRES_DB=magasinetkbh
POSTGRES_USER=postgres
POSTGRES_PASSWORD=postgres_password

# Authentication
BETTER_AUTH_SECRET=your_secret_here
BETTER_AUTH_URL=http://localhost:3000

# Application URLs
NEXT_PUBLIC_APP_URL=http://localhost:3000

# Email Configuration
SMTP_HOST=localhost
SMTP_PORT=1025
SMTP_SECURE=false

# S3/Storage Configuration
S3_ENDPOINT=http://localhost:9000
S3_ACCESS_KEY_ID=minioadmin
S3_SECRET_ACCESS_KEY=minioadmin123
S3_BUCKET_NAME=magasinetkbh-uploads
S3_REGION=us-east-1
```

### Port Configuration

| Service       | Port | Description                |
|---------------|------|----------------------------|
| Next.js App   | 3000 | Main application           |
| Next.js Debug | 9229 | Node.js debugging          |
| PostgreSQL    | 5432 | Database                   |
| MinIO API     | 9000 | File storage API           |
| MinIO Console | 9001 | File storage web interface |
| Mailpit Web   | 8025 | Email testing interface    |
| Mailpit SMTP  | 1025 | SMTP server                |

## 🛠️ Troubleshooting

### Common Issues

#### Port Conflicts
```bash
# Check what's using the ports
lsof -i :3000 -i :5432 -i :8025 -i :9000 -i :9001

# Stop conflicting services or change ports in docker-compose.yml
```

#### Docker Issues
```bash
# Check Docker status
docker info

# Clean up Docker resources
docker system prune -a
```

#### Database Issues
```bash
# Check database logs
docker compose logs postgres

# Reset database (removes volumes)
make down && docker volume prune
```

#### Application Issues
```bash
# Check application logs
docker compose logs app-node

# Rebuild application
make up --build
```

### Useful Commands

```bash
# View all service logs
docker compose logs -f

# View specific service logs
docker compose logs -f app-node
docker compose logs -f postgres

# Check service status
docker compose ps

# Execute commands in running containers
docker compose exec app-node bash
docker compose exec postgres psql -U postgres -d magasinetkbh
```

## 📁 File Structure

### Source Code Structure (`src/`)

The `src/` directory contains the main application code organized using Next.js App Router and feature-based architecture:

```
src/
├── app/                      # Next.js App Router pages and layouts
├── components/              # Reusable UI components
├── features/                # Feature-based modules (posts, comments, etc.)
├── lib/                     # Core utilities and configurations (auth, database, etc.)
├── server/                  # Server-side code (API implementations, services)
├── hooks/                   # Custom React hooks
├── config/                  # Application configuration
├── types/                   # TypeScript type definitions
├── styles/                  # Global styles
└── middleware.ts            # Next.js middleware
```

## 🔒 Security Notes

- The `.env` file contains sensitive information and should not be committed to version control.
- For production deployment, use proper secret management.
- The MinIO setup uses default credentials for local development only.

## 📚 Additional Resources

- [Next.js Documentation](https://nextjs.org/docs)
- [Drizzle ORM Documentation](https://orm.drizzle.team/)
- [Better Auth Documentation](https://www.better-auth.com/)
- [Migration Documentation](docs/MIGRATIONS.md)

---

**Happy coding! 🎉**
