package soapi

import (
	pl "simrs-vx/pkg/logger"

	d "github.com/karincake/dodol"
	"gorm.io/gorm"

	db "simrs-vx/pkg/dualtrx-helper"

	e "simrs-vx/internal/domain/main-entities/soapi"

	elog "simrs-vx/internal/domain/sync-entities/log"
	esync "simrs-vx/internal/domain/sync-entities/soapi"

	ue "simrs-vx/internal/use-case/simgos-sync-use-case/new/encounter"
)

const source = "soapi"

func Create(input e.Soapi) (*d.Data, error) {
	var (
		syncLink *esync.SoapiLink
		err      error
	)

	event := pl.Event{
		Feature: "Create",
		Source:  source,
	}

	// Start log
	pl.SetLogInfo(&event, input, "started", "create")

	// get encounter Link
	eLink, err := ue.ReadDetailLinkData(*input.Encounter_Id, &event)
	if err != nil {
		return nil, err
	}

	// get Tpendaftaran
	tPendaftaran, err := ue.ReadTPendaftaranDetailData(eLink.Simgos_Id, &event)
	if err != nil {
		return nil, err
	}

	err = db.WithDualTx(func(tx *db.Dualtx) error {
		// STEP 1: Insert to TDiagnosaDanTerapi
		tDiagTherapy, err := CreateTDiagnosaDanTerapi(input, tPendaftaran, &event, tx.Simgos)
		if err != nil {
			return err
		}

		// STEP 2: Insert to TICD
		_, err = CreateTIcd(input, tPendaftaran, &event, tx.Simgos)
		if err != nil {
			return err
		}

		// STEP 3: Insert to TICD-CM
		_, err = CreateTIcdCm(input, tPendaftaran, &event, tx.Simgos)
		if err != nil {
			return err
		}

		// STEP 4: Insert to Link
		syncLink, err = CreateLinkData(input.Id, tDiagTherapy.Idxterapi, &event, tx.Sync)
		if err != nil {
			return err
		}

		return nil
	})

	if err != nil {
		if syncLink != nil {
			go func() { _ = DeleteLinkData(syncLink, &event) }()
		}
		return nil, err
	}

	pl.SetLogInfo(&event, nil, "complete")

	return &d.Data{
		Meta: d.II{
			"source":    source,
			"structure": "single-data",
			"status":    "created",
		},
	}, nil
}

func CreateSimxLog(input elog.SimxLogDto) (*d.Data, error) {
	event := pl.Event{
		Feature: "Create",
		Source:  source,
	}

	// Start log
	pl.SetLogInfo(&event, input, "started", "create")

	tx := db.NewTx()
	err := tx.Sync.Transaction(func(tx *gorm.DB) error {
		// Insert to Log
		if err := CreateLogData(input, &event, tx); err != nil {
			return err
		}

		return nil
	})

	if err != nil {
		return nil, err
	}

	pl.SetLogInfo(&event, nil, "complete")

	return &d.Data{
		Meta: d.II{
			"source":    source,
			"structure": "single-data",
			"status":    "created",
		},
	}, nil
}

func Update(input e.Soapi) (*d.Data, error) {
	event := pl.Event{
		Feature: "Update",
		Source:  source,
	}

	// Start log
	pl.SetLogInfo(&event, input, "started", "update")

	// Get Soapi Link
	sLink, err := ReadDetailLinkData(input.Id, &event)
	if err != nil {
		return nil, err
	}

	// Get TDiagnosadanTerapi
	tDiagTherapy, err := ReadDetailTDiagnosaDanTerapi(sLink.Simgos_Id, &event)
	if err != nil {
		return nil, err
	}

	// Get Encounter Link
	eLink, err := ue.ReadDetailLinkData(*input.Encounter_Id, &event)
	if err != nil {
		return nil, err
	}

	// Get TPendaftaran
	tPendaftaran, err := ue.ReadTPendaftaranDetailData(eLink.Simgos_Id, &event)
	if err != nil {
		return nil, err
	}

	tx := db.NewTx()
	err = tx.Simgos.Transaction(func(tx *gorm.DB) error {
		// SET LOCAL
		if err = tx.Exec(`SET LOCAL simx.sync_source = 'new'`).Error; err != nil {
			return err
		}

		// Step 1: Update TDiagnosaDanTerapi
		if err = UpdateTDiagnosaDanTerapi(input, tDiagTherapy, &event, tx); err != nil {
			return err
		}

		// STEP 2: Delete TIcd
		if err = HardDeleteTIcd(tDiagTherapy.Idxdaftar, &event, tx); err != nil {
			return err
		}

		// STEP 3: Delete TIcdCm
		if err = HardDeleteTIcdCm(tDiagTherapy.Idxdaftar, &event, tx); err != nil {
			return err
		}

		// STEP 4: Insert TIcd
		if _, err = CreateTIcd(input, tPendaftaran, &event, tx); err != nil {
			return err
		}

		// STEP 5: Insert TIcd-cm
		if _, err = CreateTIcdCm(input, tPendaftaran, &event, tx); err != nil {
			return err
		}

		return nil
	})

	pl.SetLogInfo(&event, nil, "complete")

	return &d.Data{
		Meta: d.IS{
			"source":    source,
			"structure": "single-data",
			"status":    "updated",
		},
	}, nil
}

func Delete(input e.DeleteDto) (*d.Data, error) {
	var isLinkDeleted bool

	event := pl.Event{
		Feature: "Delete",
		Source:  source,
	}

	// Start log
	pl.SetLogInfo(&event, input, "started", "delete")

	// Get Soapi Link
	syncLink, err := ReadDetailLinkData(input.Id, &event)
	if err != nil {
		return nil, err
	}

	// Get TDiagnosa&Terapi
	tDiagTh, err := ReadDetailTDiagnosaDanTerapi(syncLink.Simgos_Id, &event)
	if err != nil {
		return nil, err
	}

	err = db.WithDualTx(func(tx *db.Dualtx) error {
		// STEP 1: Delete TDiagnosa&Terapi Simgos
		if err = HardDeleteTDiagnosaDanTerapi(tDiagTh, &event, tx.Simgos); err != nil {
			return err
		}

		// STEP 2: Delete TIcd
		if err = HardDeleteTIcd(tDiagTh.Idxdaftar, &event, tx.Simgos); err != nil {
			return err
		}

		// STEP 3: Delete TIcdCm
		if err = HardDeleteTIcdCm(tDiagTh.Idxdaftar, &event, tx.Simgos); err != nil {
			return err
		}

		// STEP 4: Delete Link
		err = DeleteLinkData(syncLink, &event, tx.Sync)
		if err != nil {
			return err
		}

		isLinkDeleted = true
		return nil
	})

	if err != nil {
		if isLinkDeleted {
			go func() {
				_, _ = CreateLinkData(input.Id, tDiagTh.Idxterapi, &event)
			}()
		}
		return nil, err
	}

	pl.SetLogInfo(&event, nil, "complete")

	return &d.Data{
		Meta: d.IS{
			"source":    source,
			"structure": "single-data",
			"status":    "deleted",
		},
	}, nil

}
