# User Management Service

A comprehensive user management microservice built with Go backend and React frontend, designed to integrate with the Skybridge platform architecture.

## Features

- **Full CRUD Operations**: Create, read, update, and delete users
- **Role-Based Access**: Admin, moderator, user, and viewer roles
- **User Status Management**: Active, inactive, suspended, and pending states
- **Advanced Search & Filtering**: Search by name/email, filter by role/status
- **Pagination Support**: Handle large user datasets efficiently
- **Micro-frontend Architecture**: Seamlessly integrates with the shell dashboard
- **RESTful API**: Clean, well-documented API endpoints
- **Database Migrations**: Automated schema management
- **Health Checks**: Service health and readiness endpoints
- **Audit Logging**: Track all user management operations

## Architecture

### Backend (Go)
- **Framework**: Gin HTTP framework
- **Database**: PostgreSQL with sqlx
- **Architecture**: Clean architecture with repositories and services
- **Authentication**: Header-based (development) / JWT (production)
- **Logging**: Structured logging with Zap

### Frontend (React)
- **Framework**: React 18+ with TypeScript
- **UI Library**: Mantine v7
- **Module Federation**: Webpack 5 Module Federation
- **State Management**: React hooks and context
- **HTTP Client**: Axios with interceptors

## Quick Start

### Using Docker Compose (Recommended)

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

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

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

# Stop services
docker-compose down
```

### Development Setup

#### Backend
```bash
# Navigate to user service directory
cd user

# Install dependencies
go mod download

# Set environment variables
export DB_HOST=localhost
export DB_NAME=users
export DB_USER=postgres
export DB_PASSWORD=postgres

# Run the service
go run cmd/server/main.go
```

#### Frontend
```bash
# Navigate to web directory
cd user/web

# Install dependencies
npm install

# Start development server
npm run dev
# Frontend will be available at http://localhost:3004
```

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

# The user management module will load automatically at /app/user
```

## API Endpoints

### User Management
- `GET /api/users` - List users with filters
- `POST /api/users` - Create new user
- `GET /api/users/:id` - Get user by ID
- `PUT /api/users/:id` - Update user
- `DELETE /api/users/:id` - Delete user
- `GET /api/users/email/:email` - Get user by email
- `GET /api/users/exists/:email` - Check if user exists

### Health & Status
- `GET /health` - Service health check
- `GET /ready` - Service readiness check
- `GET /api/docs` - API documentation

## Environment Variables

### Required
- `DB_HOST` - Database host (default: localhost)
- `DB_PORT` - Database port (default: 5432)
- `DB_NAME` - Database name (default: users)
- `DB_USER` - Database username
- `DB_PASSWORD` - Database password

### Optional
- `SERVER_HOST` - Server host (default: 0.0.0.0)
- `SERVER_PORT` - Server port (default: 8090)
- `APP_ENV` - Environment (development/production)
- `LOG_LEVEL` - Logging level (debug/info/warn/error)
- `AUTH_PROVIDER` - Authentication provider (header/jwt)
- `AUTH_HEADER_USER_EMAIL` - Auth header name (default: X-User-Email)

## Database Schema

### Users Table
```sql
- id (UUID, primary key)
- email (VARCHAR, unique)
- first_name, last_name (VARCHAR)
- display_name (VARCHAR, optional)
- avatar (VARCHAR, optional)
- role (ENUM: admin, moderator, user, viewer)
- status (ENUM: active, inactive, suspended, pending)
- last_login_at (TIMESTAMP, optional)
- created_at, updated_at (TIMESTAMP)
- created_by, updated_by (VARCHAR)
```

### Additional Tables
- `user_profiles` - Extended user profile information
- `user_sessions` - Session management
- `audit_events` - Audit logging

## Go Client Library

```go
package main

import (
    "github.com/RyanCopley/skybridge/user/client"
    "github.com/RyanCopley/skybridge/user/internal/domain"
)

func main() {
    // Create client
    userClient := client.NewUserClient("http://localhost:8090", "admin@example.com")
    
    // Create user
    createReq := &domain.CreateUserRequest{
        Email:     "john@example.com",
        FirstName: "John",
        LastName:  "Doe",
        Role:      "user",
        Status:    "active",
    }
    
    user, err := userClient.CreateUser(createReq)
    if err != nil {
        panic(err)
    }
    
    // List users
    listReq := &domain.ListUsersRequest{
        Status: &domain.UserStatusActive,
        Limit:  10,
    }
    
    response, err := userClient.ListUsers(listReq)
    if err != nil {
        panic(err)
    }
}
```

## Frontend Integration

The user management frontend automatically integrates with the Skybridge shell dashboard through Module Federation. It appears in the navigation under "User Management" and is accessible at `/app/user`.

### Key Components
- `UserManagement` - Main list view with search/filter
- `UserForm` - Create/edit user form
- `userService` - API client service
- Type definitions for all data models

## Development

### Running Tests
```bash
# Backend tests
go test -v ./test/...

# Frontend tests  
cd user/web
npm test
```

### Building
```bash
# Backend binary
go build -o user-service ./cmd/server

# Frontend production build
cd user/web
npm run build
```

## Deployment

### Docker
```bash
# Build image
docker build -t user-service .

# Run container
docker run -p 8090:8090 \
  -e DB_HOST=postgres \
  -e DB_PASSWORD=postgres \
  user-service
```

### Integration with Skybridge Platform
1. The user service runs on port 8090 (configurable)
2. The frontend runs on port 3004 during development
3. Module Federation automatically makes it available in the shell dashboard
4. Authentication is handled via header forwarding from the main platform

## Contributing

1. Follow the established patterns from the KMS service
2. Maintain clean architecture separation
3. Update tests for new functionality
4. Ensure frontend follows Mantine design patterns
5. Test Module Federation integration