package antrol

import (
	"context"
	"encoding/json"
	"fmt"
	"service/internal/interfaces/bpjs"
)

type Repository interface {
	GetRefPoli(ctx context.Context) ([]Poli, error)
}

type repository struct {
	client bpjs.BpjsClient
}

func NewRepository(client bpjs.BpjsClient) Repository {
	return &repository{client: client}
}

// GetRefPoli fetches referensi poli from BPJS API
//
// # This function will return an array of Poli and error if any
//
// Context is used to pass the request context to the underlying
// client
//
// The function will return an error if the request to BPJS API
// fails or if the response cannot be unmarshalled into an array
// of Poli
//
// The function will return an empty array and nil error if the request
// to BPJS API succeeds but the response is an empty array
func (r *repository) GetRefPoli(ctx context.Context) ([]Poli, error) {
	respBytes, err := r.client.DoRequest(ctx, "GET", "ref/poli", nil)
	if err != nil {
		return nil, err
	}

	var result []Poli
	if err := json.Unmarshal(respBytes, &result); err != nil {
		return nil, fmt.Errorf("failed to unmarshal ref poli antrol response: %w", err)
	}

	return result, nil
}
