# 🚀 API Service Guide

## 📖 Introduction
This API service is designed to provide a robust backend for managing products, orders, and user authentication. It integrates with BPJS for health insurance services and offers a comprehensive set of features for developers.

## 🌟 Features
- User authentication with JWT
- CRUD operations for products and orders
- Integration with BPJS services
- Swagger documentation for easy API testing
- Docker support for easy deployment

## 📋 Quick Start (5 Menit)

### 1. Setup Environment
```bash
git clone <repository-url>
cd api-service
cp .env.example .env
```

### 2. Jalankan Database & API
```bash
# Opsi A: Docker (Rekomendasi)
make docker-run

# Opsi B: Manual
go mod download
go run cmd/api/main.go
```

### 3. Akses API
- **API**: http://localhost:8080/api/v1
- **Swagger**: http://localhost:8080/swagger/index.html
- **Health Check**: http://localhost:8080/api/v1/health

## 🏗️ Struktur Project

```
api-service/
├── cmd/api/main.go          # Entry point
├── internal/               # Core business logic
│   ├── handlers/          # HTTP controllers
│   ├── models/            # Data structures
│   ├── middleware/        # Auth & error handling
│   └── routes/            # API routes
├── tools/                 # CLI generators
└── docs/                  # API documentation
```

## 🔐 Authentication

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

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

### Demo Users
| Username | Password | Role |
|----------|----------|------|
| admin    | password | admin |
| user     | password | user  |

## 🛠️ Generate Handler Baru (30 Detik)

### Cara Cepat
```bash
# Windows
tools/generate.bat product get post put delete

# Linux/Mac
./tools/generate.sh product get post put delete

# Atau langsung dengan Go
go run tools/general/generate-handler.go orders get post

go run tools/general/generate-handler.go orders/product get post

go run tools/general/generate-handler.go orders/order get post put delete dynamic search stats

go run tools/bpjs/generate-bpjs-handler.go reference/peserta get

# 1. Test generate satu service
go run tools/bpjs/generate-handler.go services-config-bpjs.yaml vclaim

# 2. Test generate semua service
go run tools/bpjs/generate-handler.go services-config-bpjs.yaml

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

### Method Tersedia
- `get` - Ambil data
- `post` - Buat data baru
- `put` - Update data
- `delete` - Hapus data

### Hasil Generate
- **Handler**: `internal/handlers/product/product.go`
- **Models**: `internal/models/product/product.go`
- **Routes**: Otomatis ditambahkan ke `/api/v1/products`

## 📊 API Endpoints

### Public (Tanpa Auth)
- `POST /api/v1/auth/login` - Login
- `POST /api/v1/auth/register` - Register
- `GET /api/v1/health` - Health check

### Protected (Dengan Auth)
- `GET /api/v1/auth/me` - Profile user
- `GET /api/v1/products` - List products
- `POST /api/v1/products` - Create product
- `GET /api/v1/products/:id` - Detail product
- `PUT /api/v1/products/:id` - Update product
- `DELETE /api/v1/products/:id` - Delete product

GET /api/v1/retribusi/dynamic
GET /api/v1/retribusi/dynamic?fields=Jenis,Pelayanan,Dinas,Tarif
GET /api/v1/retribusi/dynamic?filter[status][_eq]=active
GET /api/v1/retribusi/dynamic?filter[Jenis][_eq]=RETRIBUSI PELAYANAN KESEHATAN
GET /api/v1/retribusi/dynamic?filter[status][_eq]=active&filter[Jenis][_contains]=KESEHATAN
GET /api/v1/retribusi/dynamic?filter[_or][0][Jenis][_contains]=KESEHATAN&filter[_or][1][Jenis][_contains]=PENDIDIKAN
GET /api/v1/retribusi/dynamic?filter[date_created][_gte]=2024-01-01&filter[date_created][_lte]=2024-12-31
GET /api/v1/retribusi/dynamic?filter[Jenis][_contains]=KESEHATAN&filter[Pelayanan][_contains]=RUMAH SAKIT
GET /api/v1/retribusi/dynamic?limit=10&offset=20
GET /api/v1/retribusi/dynamic?filter[status][_neq]=deleted&filter[Tarif][_gt]=100000&filter[Jenis][_contains]=KESEHATAN&sort=-date_created&limit=50
GET /api/v1/retribusi/dynamic?filter[Dinas][_eq]=DINAS KESEHATAN
GET /api/v1/retribusi/dynamic?filter[Kode_tarif][_contains]=RS
GET /api/v1/retribusi/dynamic?filter[date_created][_gte]=2024-01-15&filter[date_created][_lt]=2024-01-16
GET /api/v1/retribusi/dynamic?filter[Uraian_1][_contains]=RAWAT INAP

Available Filter Operators
_eq - Equal
_neq - Not equal
_lt - Less than
_lte - Less than or equal
_gt - Greater than
_gte - Greater than or equal
_contains - Contains (case-insensitive)
_ncontains - Not contains
_starts_with - Starts with
_ends_with - Ends with
_in - In array
_nin - Not in array
_null - Is null
_nnull - Is not null
Available Fields for Filtering
id - Record ID
status - Status (active, draft, inactive, deleted)
Jenis - Type of retribution
Pelayanan - Service type
Dinas - Department
Kelompok_obyek - Object group
Kode_tarif - Tariff code
Tarif - Tariff amount
Satuan - Unit
Tarif_overtime - Overtime tariff
Satuan_overtime - Overtime unit
Rekening_pokok - Main account
Rekening_denda - Penalty account
Uraian_1, Uraian_2, Uraian_3 - Descriptions
date_created - Creation date
date_updated - Update date
user_created - Created by user
user_updated - Updated by user
Response Format
The endpoint returns data in this format:


{
  "message": "Data retribusi berhasil diambil",
  "data": [
    {
      "id": "uuid",
      "status": "active",
      "Jenis": "RETRIBUSI PELAYANAN KESEHATAN",
      "Pelayanan": "RAWAT INAP",
      "Dinas": "DINAS KESEHATAN",
      "Tarif": 150000,
      "date_created": "2024-01-15T10:30:00Z"
      // ... other fields
    }
  ],
  "meta": {
    "limit": 10,
    "offset": 0,
    "total": 150,
    "total_pages": 15,
    "current_page": 1,
    "has_next": true,
    "has_prev": false
  }
}


## 🧪 Development Workflow

### Perintah Penting
```bash
make watch      # Jalankan dengan hot reload
make test       # Unit tests
make itest      # Integration tests
make all        # Semua tests
make build      # Build production
```

### Update Swagger
```bash
swag init -g cmd/api/main.go --parseDependency --parseInternal   # Alternative Kedua
swag init -g cmd/api/main.go -o docs/
```

## 🔧 Environment Variables

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

### JWT Secret
```bash
JWT_SECRET=your-secret-key-change-this-in-production
```

## 🐳 Docker Commands

### Development
```bash
make docker-run          # Jalankan semua services
docker-compose down      # Stop services
```

### Production
```bash
docker build -t api-service:prod .
docker run -d -p 8080:8080 --env-file .env api-service:prod
```

## 🎯 Tips Cepat

### 1. Generate CRUD Lengkap
```bash
go run tools/generate-handler.go user get post put delete
```

### 2. Test API dengan Swagger
1. Buka http://localhost:8080/swagger/index.html
2. Login untuk dapat token
3. Klik "Authorize" dan masukkan token
4. Test semua endpoint

### 3. Debug Database
- **pgAdmin**: http://localhost:5050
- **Database**: api_service
- **User/Pass**: postgres/postgres

## 🚨 Troubleshooting

### Generate Handler Gagal
- Pastikan di root project
- Cek file `internal/routes/v1/routes.go` ada
- Pastikan permission write

### Database Connection Error
- Cek PostgreSQL running
- Verifikasi .env configuration
- Gunakan `make docker-run` untuk setup otomatis

### Token Invalid
- Login ulang untuk dapat token baru
- Token expire dalam 1 jam
- Pastikan format: `Bearer <token>`

## 📱 Contoh Integrasi Frontend

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

// Set token
axios.defaults.headers.common['Authorization'] = 
  `Bearer ${login.data.access_token}`;

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

## 🎉 Next Steps
1. ✅ Setup environment selesai
2. ✅ Generate handler pertama
3. ✅ Test dengan Swagger
4. 🔄 Tambahkan business logic
5. 🔄 Deploy ke production

---
**Total waktu setup: 5 menit** | **Generate CRUD: 30 detik** | **Testing: Langsung di Swagger**
