package patient

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	helper "simrs-vx/internal/use-case/simgos-sync-plugin/new"

	d "github.com/karincake/dodol"

	sync "simrs-vx/internal/infra/sync-consumer-cfg"

	e "simrs-vx/internal/domain/main-entities/patient"
	elog "simrs-vx/internal/domain/sync-entities/log"
)

func Create(input *e.Patient) error {
	return helper.DoJsonRequest(input, "POST", getPrefixEndpoint())
}

func CreateLog(input *elog.SimxLogDto) error {
	prefixEndpoint := getPrefixEndpoint()
	endpoint := prefixEndpoint + "/log"
	return helper.DoJsonRequest(input, "POST", endpoint)
}

func Update(input *e.Patient) error {
	prefixEndpoint := getPrefixEndpoint()
	endpoint := fmt.Sprintf("%s/%v", prefixEndpoint, input.Id)
	return helper.DoJsonRequest(input, "PATCH", endpoint)
}

func Delete(input *e.DeleteDto) error {
	prefixEndpoint := getPrefixEndpoint()
	endpoint := fmt.Sprintf("%s/%v", prefixEndpoint, input.Id)
	return helper.DoJsonRequest(input, "DELETE", endpoint)
}

func GenerateNomrPatient() (*string, error) {
	prefixEndpoint := getPrefixEndpoint()
	endpoint := fmt.Sprintf("%s/nomr", prefixEndpoint)

	req, err := http.NewRequest("POST", endpoint, nil)
	if err != nil {
		return nil, err
	}

	req.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	bodyBytes, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	if resp.StatusCode != http.StatusOK {
		errors := d.FieldError{}
		_ = json.Unmarshal(bodyBytes, &errors)

		return nil, fmt.Errorf(errors.Message)
	}

	var result map[string]any
	if err = json.Unmarshal(bodyBytes, &result); err != nil {
		return nil, err
	}

	dataMap := result["data"].(map[string]any)
	nomr := dataMap["nomr"].(string)

	return &nomr, nil
}

func getPrefixEndpoint() string {
	return fmt.Sprintf("%s%s/v1/patient", sync.O.TargetHost, sync.O.Prefix)
}
