package sep

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

type Repository interface {
	CreateSEP(ctx context.Context, req CreateSEPRequest) (*CreateSEPResponse, error)
	UpdateSEP(ctx context.Context, req UpdateSEPRequest) (string, error)
	DeleteSEP(ctx context.Context, req DeleteSEPRequest) (string, error)
	GetSEP(ctx context.Context, noSEP string) (*SEPDetailResponse, error)
}

type repository struct {
	client bpjs.BpjsClient
}

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

func (r *repository) CreateSEP(ctx context.Context, req CreateSEPRequest) (*CreateSEPResponse, error) {
	endpoint := "SEP/2.0/insert"
	decryptedBytes, err := r.client.DoRequest(ctx, "POST", endpoint, req)
	if err != nil {
		return nil, err
	}
	var result CreateSEPResponse
	return &result, json.Unmarshal(decryptedBytes, &result)
}

func (r *repository) UpdateSEP(ctx context.Context, req UpdateSEPRequest) (string, error) {
	endpoint := "SEP/2.0/update"
	decryptedBytes, err := r.client.DoRequest(ctx, "PUT", endpoint, req)
	if err != nil {
		return "", err
	}
	// Response dari update SEP biasanya hanya string nomor SEP itu sendiri
	return string(decryptedBytes), nil
}

func (r *repository) DeleteSEP(ctx context.Context, req DeleteSEPRequest) (string, error) {
	endpoint := "SEP/2.0/delete"
	// BPJS API untuk delete menggunakan POST method dengan payload spesifik
	decryptedBytes, err := r.client.DoRequest(ctx, "POST", endpoint, req)
	if err != nil {
		return "", err
	}
	// Response dari delete SEP biasanya hanya string "OK" atau pesan konfirmasi
	return string(decryptedBytes), nil
}

func (r *repository) GetSEP(ctx context.Context, noSEP string) (*SEPDetailResponse, error) {
	endpoint := fmt.Sprintf("SEP/%s", noSEP)
	decryptedBytes, err := r.client.DoRequest(ctx, "GET", endpoint, nil)
	if err != nil {
		return nil, err
	}
	var result SEPDetailResponse
	if err := json.Unmarshal(decryptedBytes, &result); err != nil {
		return nil, fmt.Errorf("failed to unmarshal SEP detail response: %w", err)
	}
	return &result, nil
}
