# 🚀 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
```

### 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

## 🧪 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
```

## 🔧 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**
