package peserta

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

	"service/internal/interfaces/bpjs"
)

type Repository interface {
	GetByNoKartu(ctx context.Context, noKartu, tglSEP string) (*PesertaData, error)
	GetByNIK(ctx context.Context, nik, tglSEP string) (*PesertaData, error)
}

type repository struct {
	client bpjs.BpjsClient
}

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

func (r *repository) GetByNoKartu(ctx context.Context, noKartu, tglSEP string) (*PesertaData, error) {
	endpoint := fmt.Sprintf("Peserta/nokartu/%s/tglSEP/%s", noKartu, tglSEP)
	respBytes, err := r.client.DoRequest(ctx, "GET", endpoint, nil)
	if err != nil {
		return nil, err
	}

	var result PesertaResponse
	if err := json.Unmarshal(respBytes, &result); err != nil {
		return nil, fmt.Errorf("failed to unmarshal peserta response: %w", err)
	}

	return &result.Peserta, nil
}

func (r *repository) GetByNIK(ctx context.Context, nik, tglSEP string) (*PesertaData, error) {
	endpoint := fmt.Sprintf("Peserta/nik/%s/tglSEP/%s", nik, tglSEP)
	respBytes, err := r.client.DoRequest(ctx, "GET", endpoint, nil)
	if err != nil {
		return nil, err
	}

	var result PesertaResponse
	if err := json.Unmarshal(respBytes, &result); err != nil {
		return nil, fmt.Errorf("failed to unmarshal peserta response: %w", err)
	}

	return &result.Peserta, nil
}
