# CLAUDE.md - User Management Service

This file provides guidance to Claude Code (claude.ai/code) when working with the User Management Service.

## Project Overview

The User Management Service is part of the Skybridge platform, providing comprehensive user management capabilities including CRUD operations, role management, and status tracking. Built with Go backend and React micro-frontend.

**Key Technologies:**
- **Backend**: Go 1.23+ with Gin router, PostgreSQL, JWT tokens
- **Frontend**: React 18+ with TypeScript, Mantine UI components
- **Module Federation**: Webpack 5 Module Federation for plugin architecture
- **Infrastructure**: Podman/Docker Compose, Nginx
- **Security**: Header-based auth (dev) / JWT (prod), RBAC permissions

## Development Commands

### Go Backend Development

```bash
# Build the service
go build -o user-service ./cmd/server

# Run with environment variables
DB_HOST=localhost DB_NAME=users DB_USER=postgres DB_PASSWORD=postgres go run cmd/server/main.go

# Run tests
go test -v ./test/...

# Tidy modules
go mod tidy
```

### React Frontend Development

```bash
# Navigate to web directory
cd web

# Install dependencies
npm install

# Start development server on port 3004
npm run dev

# Build for production
npm run build
```

### Docker Development (Recommended)

**CRITICAL**: This service uses `docker-compose` (not podman-compose like KMS).

```bash
# Start all services (PostgreSQL + User Service)
docker-compose up -d

# Start with forced rebuild after code changes
docker-compose up -d --build

# View service logs
docker-compose logs -f user-service
docker-compose logs -f postgres

# Check service health
curl http://localhost:8090/health

# Stop services
docker-compose down
```

### Full Platform Integration

```bash
# Start the main shell dashboard
cd ../../web
npm install
npm run dev  # Available at http://localhost:3000

# Start the user service frontend
cd ../user/web  
npm run dev  # Available at http://localhost:3004

# The user management module loads automatically at http://localhost:3000/app/user
```

## Database Operations

**CRITICAL**: All database operations use `docker exec` commands with container name `user-postgres`.

```bash
# Access database shell
docker exec -it user-postgres psql -U postgres -d users

# Run SQL commands
docker exec -it user-postgres psql -U postgres -c "SELECT * FROM users LIMIT 5;"

# Check tables
docker exec -it user-postgres psql -U postgres -d users -c "\dt"

# Apply migrations (handled automatically on startup)
docker exec -it user-postgres psql -U postgres -d users -f /docker-entrypoint-initdb.d/001_initial_schema.up.sql
```

## Key Architecture Patterns

### Backend Patterns
- **Repository Pattern**: Data access via interfaces (`internal/repository/interfaces/`)
- **Service Layer**: Business logic in `internal/services/`
- **Clean Architecture**: Separation of concerns with domain models
- **Middleware Chain**: CORS, auth, logging, recovery
- **Structured Logging**: Zap logger with JSON output

### Frontend Patterns
- **Micro-frontend**: Module Federation integration with shell dashboard
- **Mantine UI**: Consistent component library across platform
- **TypeScript**: Strong typing for all data models
- **Service Layer**: API client with axios and interceptors

### Integration with Skybridge Platform
- **Port Allocation**: API:8090, Frontend:3004
- **Module Federation**: Automatic registration in microfrontends.js
- **Navigation Integration**: Appears as "User Management" in shell
- **Shared Dependencies**: React, Mantine, icons shared across modules

## Important Configuration

### Required Environment Variables

```bash
# Database (Required)
DB_HOST=localhost          # Use 'postgres' for containers
DB_PORT=5432
DB_NAME=users
DB_USER=postgres
DB_PASSWORD=postgres
DB_SSLMODE=disable

# Server
SERVER_HOST=0.0.0.0
SERVER_PORT=8090

# Authentication
AUTH_PROVIDER=header       # Use 'header' for development
AUTH_HEADER_USER_EMAIL=X-User-Email
```

### API Endpoints

```bash
# Health checks
GET /health
GET /ready

# User management
GET /api/users                    # List with filters
POST /api/users                   # Create user
GET /api/users/:id               # Get by ID
PUT /api/users/:id               # Update user
DELETE /api/users/:id            # Delete user
GET /api/users/email/:email      # Get by email
GET /api/users/exists/:email     # Check existence

# Documentation
GET /api/docs                    # API documentation
```

## User Model Structure

### Core User Fields
- `id` (UUID): Primary key
- `email` (string): Unique email address
- `first_name`, `last_name` (string): Required name fields
- `display_name` (string): Optional display name
- `avatar` (string): Optional avatar URL
- `role` (enum): admin, moderator, user, viewer
- `status` (enum): active, inactive, suspended, pending
- `created_at`, `updated_at` (timestamp)
- `created_by`, `updated_by` (string): Audit fields

### Related Models
- `UserProfile`: Extended profile information
- `UserSession`: Session tracking
- `AuditEvent`: Operation logging

## Testing

### API Testing with curl

```bash
# Check health
curl http://localhost:8090/health

# Create user (requires X-User-Email header)
curl -X POST http://localhost:8090/api/users \
  -H "Content-Type: application/json" \
  -H "X-User-Email: admin@example.com" \
  -d '{
    "email": "test@example.com",
    "first_name": "Test",
    "last_name": "User", 
    "role": "user",
    "status": "active"
  }'

# List users
curl -H "X-User-Email: admin@example.com" \
  "http://localhost:8090/api/users?limit=10&status=active"
```

### Frontend Testing
- Access http://localhost:3000/app/user in the shell dashboard
- Test create, edit, delete, search, and filter functionality
- Verify Module Federation loading and navigation

## Go Client Library Usage

```go
import "github.com/RyanCopley/skybridge/user/client"

// Create client
userClient := client.NewUserClient("http://localhost:8090", "admin@example.com")

// Create user
user, err := userClient.CreateUser(&domain.CreateUserRequest{
    Email: "test@example.com",
    FirstName: "Test",
    LastName: "User",
    Role: "user",
})
```

## Build and Deployment

### Local Development
1. Start PostgreSQL: `docker-compose up -d postgres`
2. Run backend: `go run cmd/server/main.go`
3. Start frontend: `cd web && npm run dev`
4. Access via shell dashboard: http://localhost:3000/app/user

### Production Deployment
1. Build backend: `go build -o user-service ./cmd/server`
2. Build frontend: `cd web && npm run build`
3. Use Docker: `docker-compose up -d`

## Important Notes

### Development Workflow
- Database migrations run automatically on startup
- Use header-based authentication with `X-User-Email: admin@example.com`
- Frontend hot reloads on port 3004
- Module Federation integrates automatically with shell dashboard

### Container Details
- **user-postgres**: PostgreSQL on port 5433 (external), 5432 (internal)
- **user-service**: API service on port 8090
- **Frontend**: Development server on port 3004

### Integration Points
- Registered in `/web/src/microfrontends.js` as 'user'
- Navigation icon: IconUsers from Tabler Icons
- Route: `/app/user` in shell dashboard
- Category: "Administration" in navigation

### Common Issues
- Database connection: Ensure postgres container is running
- Module Federation: Frontend must be running on port 3004
- Authentication: Include X-User-Email header in all API requests
- CORS: All origins allowed in development

This service follows the same patterns as the KMS service but focuses on user management functionality with a clean, modern UI integrated into the Skybridge platform.