package questionnaireresponse

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

type Repository interface {
	GetNextQuestionnaireResponse(ctx context.Context, lastID int64) (*QuestionnaireResponseDB, error)
	SaveSatuSehatID(ctx context.Context, idx int64, fhirID string) error
	SaveSyncLog(ctx context.Context, logData QuestionnaireResponseSyncLog) error
}

type repository struct {
	dbManager database.Service
}

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

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

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

	// TODO: Sesuaikan nama tabel kuesioner Anda (contoh: skrining awal medis)
	qSimrs := query.DynamicQuery{
		From: "public.t_kuesioner",
		Filters: []query.FilterGroup{
			{
				Filters: []query.DynamicFilter{
					query.CreateFilter("idxkuesioner", query.OpGreaterThan, lastID),
				},
			},
		},
		Sort: []query.SortField{
			query.CreateAscSort("idxkuesioner"),
		},
		Limit: 1,
	}

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

func (r *repository) SaveSyncLog(ctx context.Context, logData QuestionnaireResponseSyncLog) 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{"idxkuesioner", "questionnaireresponse_id", "request_payload", "response_payload", "status", "error_message"},
		Values:  []interface{}{logData.IdxKuesioner, logData.QuestionnaireResponseID, logData.RequestPayload, logData.ResponsePayload, logData.Status, logData.ErrorMessage},
	}
	_, err = qb.ExecuteUpsert(ctx, simrsDB, "public.log_satusehat_questionnaireresponse", insertData, []string{"idxkuesioner"}, []string{"questionnaireresponse_id", "request_payload", "response_payload", "status", "error_message"})
	return err
}
