package observation

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

type Repository interface {
	GetNextObservation(ctx context.Context, lastID int64) (*ObservationDB, error)
	SaveSatuSehatID(ctx context.Context, idx int64, fhirID string) error
	SaveSyncLog(ctx context.Context, logData ObservationSyncLog) error
}

type repository struct {
	dbManager database.Service
}

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

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

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

	// TODO: Sesuaikan dengan nama tabel pemeriksaan di SIMRS Anda
	qSimrs := query.DynamicQuery{
		From: "public.t_pemeriksaan",
		Filters: []query.FilterGroup{
			{
				Filters: []query.DynamicFilter{
					query.CreateFilter("idxpemeriksaan", query.OpGreaterThan, lastID),
				},
			},
		},
		Sort: []query.SortField{
			query.CreateAscSort("idxpemeriksaan"),
		},
		Limit: 1,
	}

	err = qb.ExecuteQueryRow(ctx, simrsDB, qSimrs, &obs)
	if err != nil {
		return nil, err
	}
	return &obs, 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)
	updateData := query.UpdateData{
		Columns: []string{"status_bridging"},
		Values:  []interface{}{fhirID},
	}
	filters := []query.FilterGroup{
		query.CreateAndFilterGroup([]query.DynamicFilter{query.CreateEqualFilter("idxpemeriksaan", idx)}),
	}

	_, err = qb.ExecuteUpdate(ctx, simrsDB, "public.t_pemeriksaan", updateData, filters)
	return err
}

func (r *repository) SaveSyncLog(ctx context.Context, logData ObservationSyncLog) 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{"idxpemeriksaan", "observation_id", "request_payload", "response_payload", "status", "error_message"},
		Values: []interface{}{
			logData.IdxPemeriksaan, logData.ObservationID, logData.RequestPayload,
			logData.ResponsePayload, logData.Status, logData.ErrorMessage,
		},
	}
	conflictCols := []string{"idxpemeriksaan"}
	updateCols := []string{"observation_id", "request_payload", "response_payload", "status", "error_message"}
	_, err = qb.ExecuteUpsert(ctx, simrsDB, "public.log_satusehat_observation", insertData, conflictCols, updateCols)
	return err
}
