package poli

import (
	"context"
	"encoding/json"
	"fmt"

	"service/internal/interfaces/bpjs"
)

type Repository interface {
	GetPoli(ctx context.Context, param string) ([]PoliData, error)
}

type repository struct {
	client bpjs.BpjsClient
}

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

func (r *repository) GetPoli(ctx context.Context, param string) ([]PoliData, error) {
	endpoint := fmt.Sprintf("referensi/poli/%s", param)
	respBytes, err := r.client.DoRequest(ctx, "GET", endpoint, nil)
	if err != nil {
		return nil, err
	}

	var result struct {
		List []PoliData `json:"list"`
	}
	if err := json.Unmarshal(respBytes, &result); err != nil {
		var directList []PoliData
		if err2 := json.Unmarshal(respBytes, &directList); err2 == nil {
			return directList, nil
		}
		return nil, fmt.Errorf("failed to unmarshal apotek poli response: %w", err)
	}
	return result.List, nil
}
