package episodeofcare

import (
	"context"
	"service/internal/infrastructure/database"
	"service/pkg/utils/query"
)

type Repository interface {
	GetNextEpisodeOfCare(ctx context.Context, lastID int64) (*EpisodeOfCareDB, error)
	SaveSatuSehatID(ctx context.Context, idx int64, fhirID string) error
	SaveSyncLog(ctx context.Context, logData EpisodeOfCareSyncLog) error
}

type repository struct {
	dbManager database.Service
}

func NewRepository(dbManager database.Service) Repository {
	return &repository{dbManager: dbManager}
}

func (r *repository) GetNextEpisodeOfCare(ctx context.Context, lastID int64) (*EpisodeOfCareDB, error) {
	var ep EpisodeOfCareDB
	simrsDB, err := r.dbManager.GetSQLXDB("simrs")
	if err != nil {
		return nil, err
	}

	qb := query.NewSQLQueryBuilder(query.DBTypePostgreSQL).SetSecurityOptions(false, 0)

	// TODO: Sesuaikan nama tabel episode Anda
	qSimrs := query.DynamicQuery{
		From: "public.t_episode_perawatan",
		Filters: []query.FilterGroup{
			{
				Filters: []query.DynamicFilter{
					query.CreateFilter("idxepisode", query.OpGreaterThan, lastID),
				},
			},
		},
		Sort: []query.SortField{
			query.CreateAscSort("idxepisode"),
		},
		Limit: 1,
	}

	err = qb.ExecuteQueryRow(ctx, simrsDB, qSimrs, &ep)
	if err != nil {
		return nil, err
	}
	return &ep, nil
}

func (r *repository) SaveSatuSehatID(ctx context.Context, idx int64, fhirID string) error {
	simrsDB, err := r.dbManager.GetSQLXDB("simrs")
	if err != nil {
		return err
	}
	qb := query.NewSQLQueryBuilder(query.DBTypePostgreSQL).SetSecurityOptions(false, 0)
	_, err = qb.ExecuteUpdate(ctx, simrsDB, "public.t_episode_perawatan", query.UpdateData{Columns: []string{"status_bridging"}, Values: []interface{}{fhirID}}, []query.FilterGroup{query.CreateAndFilterGroup([]query.DynamicFilter{query.CreateEqualFilter("idxepisode", idx)})})
	return err
}

func (r *repository) SaveSyncLog(ctx context.Context, logData EpisodeOfCareSyncLog) error {
	simrsDB, err := r.dbManager.GetSQLXDB("simrs")
	if err != nil {
		return err
	}
	qb := query.NewSQLQueryBuilder(query.DBTypePostgreSQL).SetSecurityOptions(false, 0)
	insertData := query.InsertData{
		Columns: []string{"idxepisode", "episodeofcare_id", "request_payload", "response_payload", "status", "error_message"},
		Values:  []interface{}{logData.IdxEpisode, logData.EpisodeOfCareID, logData.RequestPayload, logData.ResponsePayload, logData.Status, logData.ErrorMessage},
	}
	_, err = qb.ExecuteUpsert(ctx, simrsDB, "public.log_satusehat_episodeofcare", insertData, []string{"idxepisode"}, []string{"episodeofcare_id", "request_payload", "response_payload", "status", "error_message"})
	return err
}
