package servicerequest

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

type Repository interface {
	GetNextServiceRequest(ctx context.Context, lastID int64) (*ServiceRequestDB, error)
	SaveSatuSehatID(ctx context.Context, idx int64, fhirID string) error
	SaveSyncLog(ctx context.Context, logData ServiceRequestSyncLog) error

	GetNextRadiologyServiceRequest(ctx context.Context, lastCreatedAt time.Time) (*ServiceRequestRadDB, error)
	UpdateRadiologyServiceRequestStatus(ctx context.Context, id string, fhirID string, encounterID string, status bool) error
}

type repository struct {
	dbManager database.Service
}

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

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

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

	// TODO: Sesuaikan nama tabel order lab/radiologi
	qSimrs := query.DynamicQuery{
		From: "public.t_order_lab",
		Filters: []query.FilterGroup{
			{
				Filters: []query.DynamicFilter{
					query.CreateFilter("idxorder", query.OpGreaterThan, lastID),
				},
			},
		},
		Sort: []query.SortField{
			query.CreateAscSort("idxorder"),
		},
		Limit: 1,
	}

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

func (r *repository) SaveSyncLog(ctx context.Context, logData ServiceRequestSyncLog) 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{"idxorder", "servicerequest_id", "request_payload", "response_payload", "status", "error_message"},
		Values:  []interface{}{logData.IdxOrder, logData.ServiceRequestID, logData.RequestPayload, logData.ResponsePayload, logData.Status, logData.ErrorMessage},
	}
	_, err = qb.ExecuteUpsert(ctx, simrsDB, "public.log_satusehat_servicerequest", insertData, []string{"idxorder"}, []string{"servicerequest_id", "request_payload", "response_payload", "status", "error_message"})
	return err
}

func (r *repository) GetNextRadiologyServiceRequest(ctx context.Context, lastCreatedAt time.Time) (*ServiceRequestRadDB, error) {
	var data ServiceRequestRadDB
	satudataDB, err := r.dbManager.GetSQLXDB("satudata")
	if err != nil {
		return nil, err
	}

	qb := query.NewSQLQueryBuilder(query.DBTypePostgreSQL).SetSecurityOptions(false, 0)
	qRadiology := query.DynamicQuery{
		From:    "public.data_service_requests",
		Aliases: "dsr",
		Fields: []query.SelectField{
			{Expression: "dsr.id"},
			{Expression: `dsr."Json_data"`, Alias: "Json_data"},
			{Expression: `dkp."Nomor_satusehat_pasien"`, Alias: "Nomor_satusehat_pasien"},
			{Expression: `dkp."Nama_lengkap"`, Alias: "Nama_lengkap"},
			{Expression: `dkp."IDXDAFTAR_satusehat"`, Alias: "IDXDAFTAR_satusehat"},
			{Expression: `dsr."Created_at"`, Alias: "Created_at"},
			{Expression: `dp."Kode_satusehat"`, Alias: "requester_id"},
		},
		Joins: []query.Join{
			{
				Type:  "INNER",
				Table: "public.data_kunjungan_pasien",
				Alias: "dkp",
				OnConditions: query.CreateAndFilterGroup([]query.DynamicFilter{
					query.CreateFilter(`dsr."No_register"`, query.OpEqual, `dkp."NOMR"`),
					query.CreateFilter(`dsr."Tanggal_order"`, query.OpEqual, `dkp."Tanggal_masuk"`),
				}),
			},
			{
				Type:  "LEFT",
				Table: "public.data_pegawai",
				Alias: "dp",
				OnConditions: query.CreateAndFilterGroup([]query.DynamicFilter{
					query.CreateFilter(`dkp."DPJP"`, query.OpEqual, `dp."id"`),
				}),
			},
		},
		Filters: []query.FilterGroup{
			{Filters: []query.DynamicFilter{
				query.CreateFilter(`dsr."Send_status"`, query.OpEqual, "false"),
				query.CreateFilter(`dsr."Created_at"`, query.OpGreaterThan, lastCreatedAt),
				query.CreateFilter(`dsr."Order_from"`, query.OpEqual, "radiologi"),
			}},
		},
		Sort:  []query.SortField{query.CreateAscSort(`dsr."Created_at"`)},
		Limit: 1,
	}

	err = qb.ExecuteQueryRow(ctx, satudataDB, qRadiology, &data)
	return &data, err
}

func (r *repository) UpdateRadiologyServiceRequestStatus(ctx context.Context, id string, fhirID string, encounterID string, status bool) error {
	satudataDB, err := r.dbManager.GetSQLXDB("satudata")
	if err != nil {
		return err
	}

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

	// Secara eksplisit mengizinkan kolom yang memiliki case sensitive (huruf besar) dengan quotes
	qb.SetAllowedColumns([]string{
		`"Entity_Id"`, `"Send_status"`, "id", `"Encounter_Id"`,
	})

	statusStr := "false"
	if status {
		statusStr = "true"
	}

	updateData := query.UpdateData{
		Columns: []string{`"Entity_Id"`, `"Send_status"`, `"Encounter_Id"`},
		Values:  []interface{}{fhirID, statusStr, encounterID},
	}
	filters := []query.FilterGroup{query.CreateAndFilterGroup([]query.DynamicFilter{query.CreateEqualFilter("id", id)})}
	_, err = qb.ExecuteUpdate(ctx, satudataDB, "public.data_service_requests", updateData, filters)
	return err
}
