
# 🚀 API Service - Clean Architecture

> **Layanan API modern dengan arsitektur bersih untuk manajemen produk, pesanan, dan otentikasi pengguna**

## 📑 Daftar Isi

- [✨ Fitur Utama](#-fitur-utama)
- [🏗️ Arsitektur](#%EF%B8%8F-arsitektur)
- [⚡ Quick Start](#-quick-start)
- [🔐 Autentikasi](#-autentikasi)
- [📊 API Endpoints](#-api-endpoints)
- [🛠️ Development](#%EF%B8%8F-development)
- [🚀 Deployment](#-deployment)
- [📚 Dokumentasi](#-dokumentasi)

***

## ✨ Fitur Utama

### Core Features

- **🔒 JWT Authentication** - Sistem autentikasi yang aman
- **📦 CRUD Operations** - Operasi lengkap untuk produk dan pesanan
- **🏥 BPJS Integration** - Integrasi dengan layanan kesehatan BPJS
- **🩺 FHIR/SATUSEHAT** - Dukungan standar kesehatan internasional
- **📖 API Documentation** - Swagger/OpenAPI yang interaktif


### Developer Experience

- **🔥 Hot Reload** - Development dengan auto-restart
- **🐳 Docker Ready** - Deployment yang mudah
- **⚡ Code Generator** - Buat handler dan model otomatis
- **🧪 Testing Suite** - Unit dan integration tests
- **📊 Health Monitoring** - Monitoring kesehatan aplikasi

***

## 🏗️ Arsitektur

### Clean Architecture Layers

```
┌─────────────────────────────────────┐
│           Presentation Layer        │  ← handlers/, routes/
├─────────────────────────────────────┤
│           Application Layer         │  ← middleware/, validators/
├─────────────────────────────────────┤
│              Domain Layer           │  ← models/, interfaces/
├─────────────────────────────────────┤
│          Infrastructure Layer       │  ← database/, external APIs
└─────────────────────────────────────┘
```


### Struktur Project

```
api-service/
├── 📁 cmd/
│   └── api/main.go                 # 🚪 Entry point aplikasi
├── 📁 internal/                    # 🏠 Core business logic
│   ├── handlers/                   # 🎮 HTTP controllers (Presentation)
│   ├── middleware/                 # 🛡️ Auth & validation (Application)
│   ├── models/                     # 📊 Data structures (Domain)
│   ├── routes/                     # 🛣️ API routing (Presentation)
│   ├── services/                   # 💼 Business logic (Application)
│   └── repository/                 # 💾 Data access (Infrastructure)
├── 📁 tools/                       # 🔧 Development tools
│   ├── general/                    # 🎯 General generators
│   ├── bpjs/                       # 🏥 BPJS specific tools
│   └── satusehat/                  # 🩺 SATUSEHAT tools
├── 📁 docs/                        # 📚 Documentation
├── 📁 configs/                     # ⚙️ Configuration files
└── 📁 scripts/                     # 📜 Automation scripts
```


***

## ⚡ Quick Start

### 1️⃣ Setup Environment (2 menit)

```bash
# Clone repository
git clone <repository-url>
cd api-service

# Setup environment
cp .env.example .env
```


### 2️⃣ Pilih Method Setup

**🐳 Docker (Recommended)**

```bash
make docker-run
```

**🔧 Manual Setup**

```bash
# Install dependencies
go mod download

# Run database migrations
make migrate-up

# Start server
go run cmd/api/main.go
```


### 3️⃣ Verify Installation

| Service | URL | Status |
| :-- | :-- | :-- |
| **API** | http://localhost:8080/api/v1 | ✅ |
| **Swagger** | http://localhost:8080/swagger/index.html | 📖 |
| **Health Check** | http://localhost:8080/api/v1/health | 💚 |


***

## 🔐 Autentikasi

### Login \& Mendapatkan Token

```bash
curl -X POST http://localhost:8080/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": "admin",
    "password": "password"
  }'
```

**Response:**

```json
{
  "access_token": "eyJhbGciOiJIUzI1NiIs...",
  "expires_in": 3600,
  "user": {
    "id": "123",
    "username": "admin",
    "role": "admin"
  }
}
```


### Menggunakan Token

```bash
curl -X GET http://localhost:8080/api/v1/products \
  -H "Authorization: Bearer <your-token>"
```


### Demo Accounts

| Username | Password | Role | Akses |
| :-- | :-- | :-- | :-- |
| `admin` | `password` | Admin | Semua endpoint |
| `user` | `password` | User | Read-only |


***

## 📊 API Endpoints

### 🌍 Public Endpoints

| Method | Endpoint | Deskripsi |
| :-- | :-- | :-- |
| `POST` | `/api/v1/auth/login` | Login pengguna |
| `POST` | `/api/v1/auth/register` | Registrasi pengguna baru |
| `GET` | `/api/v1/health` | Status kesehatan API |

### 🔒 Protected Endpoints

#### User Management

| Method | Endpoint | Deskripsi |
| :-- | :-- | :-- |
| `GET` | `/api/v1/auth/me` | Profile pengguna |
| `PUT` | `/api/v1/auth/me` | Update profile |

#### Product Management

| Method | Endpoint | Deskripsi |
| :-- | :-- | :-- |
| `GET` | `/api/v1/products` | List semua produk |
| `POST` | `/api/v1/products` | Buat produk baru |
| `GET` | `/api/v1/products/:id` | Detail produk |
| `PUT` | `/api/v1/products/:id` | Update produk |
| `DELETE` | `/api/v1/products/:id` | Hapus produk |

#### Dynamic Query (Advanced)

| Method | Endpoint | Deskripsi |
| :-- | :-- | :-- |
| `GET` | `/api/v1/retribusi/dynamic` | Query dengan filter dinamis |

**Contoh Query:**

```bash
# Filter berdasarkan jenis
GET /api/v1/retribusi/dynamic?filter[Jenis][_eq]=RETRIBUSI PELAYANAN KESEHATAN

# Kombinasi filter
GET /api/v1/retribusi/dynamic?filter[status][_eq]=active&filter[Tarif][_gt]=100000

# Pagination dan sorting
GET /api/v1/retribusi/dynamic?sort=-date_created&limit=10&offset=20
```


### 🏥 BPJS Integration

| Method | Endpoint | Deskripsi |
| :-- | :-- | :-- |
| `GET` | `/api/v1/bpjs/peserta/:no` | Data peserta BPJS |
| `GET` | `/api/v1/bpjs/rujukan/:no` | Data rujukan |

### 🩺 SATUSEHAT Integration

| Method | Endpoint | Deskripsi |
| :-- | :-- | :-- |
| `GET` | `/api/v1/satusehat/patient/:id` | Data pasien |
| `POST` | `/api/v1/satusehat/encounter` | Buat encounter baru |


***

## 🛠️ Development

### Code Generation (30 detik)

**🎯 Generate CRUD Lengkap**

```bash
# Generate handler untuk entity baru
go run tools/general/generate-handler.go product get post put delete

# Generate dengan fitur advanced
go run tools/general/generate-handler.go orders get post put delete dynamic search stats
```

**🏥 Generate BPJS Handler**

```bash
# Single service
go run tools/bpjs/generate-bpjs-handler.go reference/peserta get

# Semua service dari config
go run tools/bpjs/generate-handler.go services-config-bpjs.yaml
```

**🩺 Generate SATUSEHAT Handler**

```bash
go run tools/satusehat/generate-satusehat-handler.go services-config-satusehat.yaml patient
```


### Development Commands

```bash
# 🔥 Development dengan hot reload
make watch

# 🧪 Testing
make test           # Unit tests
make itest          # Integration tests
make test-all       # Semua tests

# 📖 Update dokumentasi
make docs           # Generate Swagger docs

# 🔍 Code quality
make lint           # Linting
make format         # Format code
```


### Environment Configuration

**📁 .env File:**

```bash
# Database
BLUEPRINT_DB_HOST=localhost
BLUEPRINT_DB_PORT=5432
BLUEPRINT_DB_USERNAME=postgres
BLUEPRINT_DB_PASSWORD=postgres
BLUEPRINT_DB_DATABASE=api_service

# JWT
JWT_SECRET=your-super-secret-key-change-in-production

# External APIs
BPJS_BASE_URL=https://api.bpjs-kesehatan.go.id
SATUSEHAT_BASE_URL=https://api.satusehat.kemkes.go.id

# Application
APP_ENV=development
APP_PORT=8080
LOG_LEVEL=debug
```


***

## 🚀 Deployment

### 🐳 Docker Deployment

**Development:**

```bash
# Start semua services
make docker-run

# Stop services
make docker-down

# Rebuild dan restart
make docker-rebuild
```

**Production:**

```bash
# Build production image
docker build -t api-service:prod .

# Run production container
docker run -d \
  --name api-service \
  -p 8080:8080 \
  --env-file .env.prod \
  api-service:prod
```


### 🔧 Manual Deployment

```bash
# Build aplikasi
make build

# Run migrations
./scripts/migrate.sh up

# Start server
./bin/api-service
```


***

## 📚 Dokumentasi

### 📖 Interactive API Documentation

Kunjungi **Swagger UI** di: http://localhost:8080/swagger/index.html

**Cara menggunakan:**

1. 🔑 Login melalui `/auth/login` endpoint
2. 📋 Copy token dari response
3. 🔓 Klik tombol "Authorize" di Swagger
4. 📝 Masukkan: `Bearer <your-token>`
5. ✅ Test semua endpoint yang tersedia

### 🧪 Testing Examples

**JavaScript/Axios:**

```javascript
// Login dan set token
const auth = await axios.post('/api/v1/auth/login', {
  username: 'admin',
  password: 'password'
});

axios.defaults.headers.common['Authorization'] = 
  `Bearer ${auth.data.access_token}`;

// Fetch data
const products = await axios.get('/api/v1/products');
console.log(products.data);
```

**cURL Examples:**

```bash
# Login
TOKEN=$(curl -s -X POST http://localhost:8080/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username":"admin","password":"password"}' | jq -r '.access_token')

# Use token
curl -H "Authorization: Bearer $TOKEN" \
  http://localhost:8080/api/v1/products
```


### 🔍 Health Monitoring

```bash
# Basic health check
curl http://localhost:8080/api/v1/health

# Detailed system info
curl http://localhost:8080/api/v1/health/detailed
```

**Response:**

```json
{
  "status": "healthy",
  "timestamp": "2025-09-10T05:39:00Z",
  "services": {
    "database": "connected",
    "bpjs_api": "accessible",
    "satusehat_api": "accessible"
  },
  "version": "1.0.0"
}
```


***

## 🚨 Troubleshooting

### Masalah Umum

**❌ Database Connection Error**

```bash
# Cek status PostgreSQL
make db-status

# Reset database
make db-reset

# Check logs
make logs-db
```

**❌ Generate Handler Gagal**

- ✅ Pastikan berada di root project
- ✅ Cek permission write di folder `internal/`
- ✅ Verifikasi file `internal/routes/v1/routes.go` exists

**❌ Token Invalid/Expired**

- 🔄 Login ulang untuk mendapatkan token baru
- ⏰ Token expire dalam 1 jam (configurable)
- 📝 Format harus: `Bearer <token>`

**❌ Import Error saat Generate**

- 🧹 Jalankan: `go mod tidy`
- 🔄 Restart development server
- 📝 Cek format import di generated files


### Debug Mode

```bash
# Enable debug logging
export LOG_LEVEL=debug

# Run dengan verbose output
make run-debug

# Monitor performance
make monitor
```


***

## 🎯 Next Steps

### 📋 Development Roadmap

- [ ] ✅ **Setup environment selesai**
- [ ] ✅ **Generate handler pertama**
- [ ] ✅ **Test dengan Swagger**
- [ ] 🔄 **Implementasi business logic**
- [ ] 🔄 **Tambahkan unit tests**
- [ ] 🔄 **Setup CI/CD pipeline**
- [ ] 🔄 **Deploy ke production**


### 🚀 Advanced Features

- **📊 Monitoring \& Observability**
- **🔒 Enhanced Security (Rate limiting, CORS)**
- **📈 Performance Optimization**
- **🌐 Multi-language Support**
- **📱 Mobile SDK Integration**

***

**⚡ Total setup time: 5 menit | 🔧 Generate CRUD: 30 detik | 🧪 Testing: Langsung via Swagger**

> **💡 Pro Tip:** Gunakan `make help` untuk melihat semua command yang tersedia

***

