package dpho

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

	"service/internal/interfaces/bpjs"
)

type Repository interface {
	GetDPHO(ctx context.Context) ([]DPHOData, error)
}

type repository struct {
	client bpjs.BpjsClient
}

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

func (r *repository) GetDPHO(ctx context.Context) ([]DPHOData, error) {
	respBytes, err := r.client.DoRequest(ctx, "GET", "referensi/dpho", nil)
	if err != nil {
		return nil, err
	}

	// Coba parsing ke dalam format object { "list": [...] }
	var result struct {
		List []DPHOData `json:"list"`
	}
	if err := json.Unmarshal(respBytes, &result); err != nil {
		// Fallback jika API mengembalikan array langsung [...]
		var directList []DPHOData
		if err2 := json.Unmarshal(respBytes, &directList); err2 == nil {
			return directList, nil
		}
		return nil, fmt.Errorf("failed to unmarshal apotek dpho response: %w", err)
	}
	return result.List, nil
}
