package bed

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

	"service/internal/interfaces/bpjs"
)

type Repository interface {
	Read(ctx context.Context, kdPpk string, start, limit int) ([]BedData, error)
	Create(ctx context.Context, kdPpk string, payload BedData) error
	Update(ctx context.Context, kdPpk string, payload BedData) error
	Delete(ctx context.Context, kdPpk string, payload BedDeletePayload) error
}

type repository struct {
	client bpjs.BpjsClient
}

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

func (r *repository) Read(ctx context.Context, kdPpk string, start, limit int) ([]BedData, error) {
	endpoint := fmt.Sprintf("rest/bed/read/%s/%d/%d", kdPpk, start, limit)
	respBytes, err := r.client.DoRequest(ctx, "GET", endpoint, nil)
	if err != nil {
		return nil, err
	}

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

	return result.List, nil
}

func (r *repository) Create(ctx context.Context, kdPpk string, payload BedData) error {
	endpoint := fmt.Sprintf("rest/bed/create/%s", kdPpk)
	_, err := r.client.DoRequest(ctx, "POST", endpoint, payload)
	// Aplicares biasanya mengembalikan sukses di metadata yang sudah dihandle oleh client.go
	return err
}

func (r *repository) Update(ctx context.Context, kdPpk string, payload BedData) error {
	// Endpoint Update Aplicares menggunakan method POST, bukan PUT
	endpoint := fmt.Sprintf("rest/bed/update/%s", kdPpk)
	_, err := r.client.DoRequest(ctx, "POST", endpoint, payload)
	return err
}

func (r *repository) Delete(ctx context.Context, kdPpk string, payload BedDeletePayload) error {
	// Endpoint Delete Aplicares juga menggunakan method POST
	endpoint := fmt.Sprintf("rest/bed/delete/%s", kdPpk)
	_, err := r.client.DoRequest(ctx, "POST", endpoint, payload)
	return err
}
