package medication

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

type Repository interface {
	GetNextMedication(ctx context.Context, lastID int64) (*MedicationDB, error)
	SaveSatuSehatID(ctx context.Context, idxPesanObat int64, fhirID string) error
	SaveSyncLog(ctx context.Context, logData MedicationSyncLog) error
}

type repository struct {
	dbManager database.Service
}

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

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

	qb := query.NewSQLQueryBuilder(query.DBTypePostgreSQL).
		SetSecurityOptions(false, 0).
		SetQueryLogging(false).
		SetAllowedColumns([]string{"idxpesanobat", "kode_kfa", "tgl_pesan"})

	// startDate, _ := time.Parse("2006-01-02", "2026-01-02")

	qSimrs := query.DynamicQuery{
		From: "public.t_permintaan_apotek_rajal",
		Fields: []query.SelectField{
			{Expression: "idxpesanobat"},
			{Expression: "kode_kfa"},
		},
		Filters: []query.FilterGroup{
			{
				Filters: []query.DynamicFilter{
					query.CreateFilter("idxpesanobat", query.OpGreaterThanEqual, lastID+1),
					// query.CreateFilter("tgl_pesan", query.OpGreaterThanEqual, startDate),
				},
			},
		},
		Sort: []query.SortField{
			query.CreateAscSort("idxpesanobat"),
		},
		Limit: 1,
	}

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

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

func (r *repository) SaveSyncLog(ctx context.Context, logData MedicationSyncLog) error {
	simrsDB, err := r.dbManager.GetSQLXDB("simrs")
	if err != nil {
		return err
	}
	qb := query.NewSQLQueryBuilder(query.DBTypePostgreSQL).
		SetSecurityOptions(false, 0).
		SetQueryLogging(false).
		SetAllowedColumns([]string{"idxpesanobat", "satusehat_id", "request_payload", "response_payload", "status", "error_message"})
	insertData := query.InsertData{
		Columns: []string{"idxpesanobat", "satusehat_id", "request_payload", "response_payload", "status", "error_message"},
		Values:  []interface{}{logData.IdxPesanObat, logData.SatuSehatID, logData.RequestPayload, logData.ResponsePayload, logData.Status, logData.ErrorMessage},
	}
	_, err = qb.ExecuteUpsert(ctx, simrsDB, "public.log_satusehat_medication", insertData, []string{"idxpesanobat"}, []string{"satusehat_id", "request_payload", "response_payload", "status", "error_message"})
	return err
}
