# MaplePress Backend - Getting Started

Complete guide for local development in under 5 minutes.

---

## Quick Start

### Prerequisites

- Docker and Docker Compose installed
- Go 1.21+ installed
- Task (Taskfile) installed: `brew install go-task/tap/go-task`

### Start Development (3 steps)

```bash
# 1. Start infrastructure (in separate terminal)
cd ../infrastructure/development
task dev:start
# Wait ~1 minute for services to be ready

# 2. Start backend (in this directory)
cd ../maplepress-backend
task dev
# Backend runs at http://localhost:8000
# Press Ctrl+C to stop
# Auto-migration and hot-reload are enabled

# 3. Verify it's running
curl http://localhost:8000/health
# Should return: {"status":"healthy"}
```

---

## Create Test Data

### 1. Register a User

```bash
# Create user and tenant
curl -X POST http://localhost:8000/api/v1/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@example.com",
    "password": "TestPassword123!",
    "name": "Test User",
    "tenant_name": "Test Organization",
    "tenant_slug": "test-org"
  }'
```

**Save the `access_token` from the response!**

```bash
# Export your token for subsequent requests
export TOKEN="eyJhbGci..."
```

### 2. Create a WordPress Site

```bash
# Tenant is automatically determined from JWT token
curl -X POST http://localhost:8000/api/v1/sites \
  -H "Content-Type: application/json" \
  -H "Authorization: JWT $TOKEN" \
  -d '{
    "domain": "localhost:8081",
    "site_url": "http://localhost:8081"
  }'
```

**Save the `api_key` from the response!** (Shown only once)

### 3. Test Plugin Authentication

```bash
# Test the API key (what WordPress plugin uses)
curl -X GET http://localhost:8000/api/v1/plugin/status \
  -H "Authorization: Bearer YOUR_API_KEY_HERE"
```

---

## Common Commands

### Development Workflow

```bash
# Start backend (foreground, see logs)
task dev

# Restart after code changes
# CompileDaemon auto-rebuilds on file changes
# Only manually restart if needed:
# Press Ctrl+C, then:
task dev

# Stop backend
# Press Ctrl+C (or task dev:down in another terminal)
```

### Database

```bash
# Clear database (WARNING: deletes all data!)
task db:clear

# Manual migration (only if auto-migrate disabled)
task migrate:up

# View database
cd ../infrastructure/development
task cql
# Inside cqlsh:
USE maplepress;
SELECT * FROM sites_by_id;
```

### Testing

```bash
# Run tests
task test

# Format code
task format

# Run linters
task lint
```

### API Operations

```bash
# Export your token first
export TOKEN="your_jwt_token_here"

# Get your profile
curl http://localhost:8000/api/v1/me \
  -H "Authorization: JWT $TOKEN"

# List sites
curl http://localhost:8000/api/v1/sites \
  -H "Authorization: JWT $TOKEN"

# Get specific site
curl http://localhost:8000/api/v1/sites/SITE_ID \
  -H "Authorization: JWT $TOKEN"

# Delete site
curl -X DELETE http://localhost:8000/api/v1/sites/SITE_ID \
  -H "Authorization: JWT $TOKEN"
```

---

## WordPress Plugin Setup

### 1. Access WordPress Admin

```bash
# WordPress is running at:
http://localhost:8081/wp-admin
# Default credentials: admin / admin
```

### 2. Configure MaplePress Plugin

1. Navigate to **Settings → MaplePress**
2. Enter:
   - **API URL**: `http://maplepress-backend-dev:8000`
   - **API Key**: Your site API key from step 2 above
3. Click **Save Settings & Verify Connection**

**Note**: Use `http://maplepress-backend-dev:8000` (not `localhost`) because WordPress runs in Docker and needs the container name.

---

## Troubleshooting

### Backend won't start

**Error**: "Infrastructure not running!"

**Solution**:
```bash
cd ../infrastructure/development
task dev:start
# Wait for services to be healthy (~1 minute)
```

### Token expired (401 Unauthorized)

Tokens expire after 60 minutes. Login again:

```bash
curl -X POST http://localhost:8000/api/v1/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@example.com",
    "password": "TestPassword123!"
  }'
```

### WordPress can't connect to backend

**Error**: "Could not resolve host"

**Solution**: Make sure you're using `http://maplepress-backend-dev:8000` (not `localhost:8000`) in WordPress settings.

**Verify from WordPress container**:
```bash
docker exec mapleopentech-wordpress-dev curl http://maplepress-backend-dev:8000/health
# Should return: {"status":"healthy"}
```

---

## Architecture Overview

```
Backend (Port 8000)
├── HTTP Server
├── JWT Authentication (user access)
├── API Key Authentication (plugin access)
├── Domain Layer (business logic)
├── Repository Layer (data access)
└── Infrastructure
    ├── Cassandra (primary database)
    ├── Redis (caching)
    ├── Meilisearch (search indexing)
    └── SeaweedFS (S3-compatible storage)
```

### Key Concepts

- **Tenant**: Organization/account that can have multiple users and sites
- **User**: Person who logs in with email/password (gets JWT token)
- **Site**: WordPress installation (gets API key for plugin authentication)
- **Multi-tenancy**: All data is scoped to a tenant_id
- **JWT Token**: Used by dashboard/admin users (Authorization: JWT ...)
- **API Key**: Used by WordPress plugins (Authorization: Bearer ...)

---

## API Endpoints

### Public (No Auth)
- `GET /health` - Health check
- `POST /api/v1/register` - Register user + tenant
- `POST /api/v1/login` - Login

### Authenticated (JWT Required)
- `GET /api/v1/me` - Get user profile
- `POST /api/v1/sites` - Create site
- `GET /api/v1/sites` - List sites
- `GET /api/v1/sites/{id}` - Get site
- `DELETE /api/v1/sites/{id}` - Delete site
- `POST /api/v1/sites/{id}/rotate-key` - Rotate API key

### Plugin (API Key Required)
- `GET /api/v1/plugin/status` - Verify API key and get site info

**Full API documentation**: See `API.md`

---

## Environment Variables

The backend uses `.env` for configuration. Copy from sample:

```bash
cp .env.sample .env
```

**Key variables**:

```bash
# Application
APP_JWT_SECRET=change-me-in-production
SERVER_PORT=8000

# Database (Cassandra)
DATABASE_HOSTS=localhost
DATABASE_KEYSPACE=maplepress

# Cache (Redis)
CACHE_HOST=localhost
CACHE_PORT=6379
```

For Docker development, the `docker-compose.dev.yml` sets these automatically.

---

## Next Steps

- **API Documentation**: See `API.md` for complete endpoint reference
- **Architecture**: See `DEVELOPER_GUIDE.md` for code structure
- **WordPress Plugin**: See `native/wordpress/maplepress-plugin/README.md`

---

## Quick Reference

```bash
# Infrastructure
cd ../infrastructure/development
task dev:start          # Start all services
task dev:stop           # Stop all services
task cql                # Open Cassandra shell

# Backend
cd ../maplepress-backend
task dev                # Start backend (auto-migrate + hot-reload)
task dev:down           # Stop backend
task db:clear           # Clear database
task test               # Run tests
task build              # Build binary (only for manual operations)
task migrate:up         # Manual migration (only if needed)

# View infrastructure logs
docker logs mapleopentech-cassandra-1-dev    # Cassandra logs
docker logs mapleopentech-redis-dev          # Redis logs
```

---

**Happy coding!** 🚀

For questions or issues, see the full documentation or check the [GitHub repository](https://codeberg.org/mapleopentech/monorepo).
