package patient

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

	"gorm.io/gorm"

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

// example of middleware
func init() {
	createPreMw = append(createPreMw,
		createMw{Name: "check-vclaim-member", Func: checkVclaimMember})

	createSimxSyncMw = append(createSimxSyncMw,
		createSyncMw{Name: "sync-create-patient", Func: plugin.Create})

	createSimxLogMw = append(createSimxLogMw,
		createLogMw{Name: "create-sync-log", Func: plugin.CreateLog})

	updatePreMw = append(updatePreMw,
		updateMw{Name: "sync-update-patient", Func: plugin.Update})

	deletePreMw = append(deletePreMw,
		deleteMw{Name: "sync-delete-patient", Func: plugin.Delete})

	generatePatientNumber = generateNumberMw{Name: "generate-nomr-patient", Func: plugin.GenerateNomrPatient}
}

func checkVclaimMember(input *e.CreateDto, data *e.Patient, tx *gorm.DB) error {
	if input.Person.VclaimMember_CardNumber != nil && input.Person.ResidentIdentityNumber != nil {
		return isVclaimMemberMatch(input)
	}
	return nil
}

func isVclaimMemberMatch(input *e.CreateDto) error {
	endpoint := endpointMapper(*input.Person.VclaimMember_CardNumber)
	req, err := http.NewRequest("GET", endpoint, nil)
	if err != nil {
		return err
	}
	req.Header.Set("Content-Type", "application/json")

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

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

	var data BPJSResponse

	if err := json.Unmarshal(body, &data); err != nil {
		return fmt.Errorf("failed to parse response JSON: %w", err)
	}

	if data.MetaData.Code != "200" {
		return fmt.Errorf("failed to get vclaim member: %s", data.MetaData.Message)
	}

	if data.Response.Peserta.NoKartu == "" || data.Response.Peserta.NIK == "" {
		return fmt.Errorf("failed to get vclaim member: noKartu or nik is empty")
	}

	if data.Response.Peserta.NIK != *input.Person.ResidentIdentityNumber {
		return fmt.Errorf("nik(residentIdentityNumber) is not match with bpjs number(vclaimMember_cardNumber)")
	}
	return nil
}
