package imagingstudy

import (
	"context"
	"database/sql"

	"service/internal/infrastructure/database"
)

type Repository interface {
	GetNextPendingRequest(ctx context.Context) (*ImagingStudyData, error)
	UpdateSyncStatus(ctx context.Context, reqID string, status string, responsePayload string) error
}

type repository struct {
	dbManager database.Service
}

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

// GetNextPendingRequest mengambil 1 data service request radiologi yang belum terkirim
func (r *repository) GetNextPendingRequest(ctx context.Context) (*ImagingStudyData, error) {
	var data ImagingStudyData

	// 1. Ambil koneksi Postgres (Satu Data) - Sesuaikan nama dengan konfigurasi Anda
	pgDB, err := r.dbManager.GetDB("satudata")
	if err != nil {
		return nil, err
	}

	// Ambil dari Postgres
	queryPG := `
		SELECT 
			sr.id, sr."Entity_Id", sr."Encounter_Id", sr."No_register",
			kp."Nomor_satusehat_pasien", kp."Nama_lengkap"
		FROM public.data_service_requests sr
		JOIN public.data_kunjungan_pasien kp ON sr."Encounter_Id" = kp."IDXDAFTAR_satusehat"
		WHERE LOWER(sr."Order_from") = 'radiologi' 
		  AND (sr."Send_status" IS NULL OR sr."Send_status" = 'FAILED')
		ORDER BY sr."Created_at" ASC
		LIMIT 1
	`
	err = pgDB.QueryRowContext(ctx, queryPG).Scan(
		&data.RequestID, &data.ServiceRequestID, &data.EncounterID, &data.NoRegister,
		&data.PatientID, &data.PatientName,
	)
	if err != nil { // Bisa berupa sql.ErrNoRows jika data habis
		return nil, err
	}

	// 2. Ambil koneksi MySQL (RIS) - Sesuaikan nama dengan konfigurasi Anda
	mySQLDB, err := r.dbManager.GetDB("simrs")
	if err == nil && data.NoRegister.Valid {
		queryMySQL := `SELECT modality, foto FROM periksa WHERE noregister = ? LIMIT 1`

		var modality sql.NullString
		var foto sql.NullTime

		// Gunakan placeholder '?' jika MySQL, atau '$1' jika PostgreSQL
		err = mySQLDB.QueryRowContext(ctx, queryMySQL, data.NoRegister.String).Scan(&modality, &foto)
		if err == nil {
			data.Modality = modality
			data.StartedDate = foto
		}
	}

	return &data, nil
}

// UpdateSyncStatus memperbarui status pengiriman di PostgreSQL
func (r *repository) UpdateSyncStatus(ctx context.Context, reqID string, status string, responsePayload string) error {
	pgDB, err := r.dbManager.GetDB("satudata")
	if err != nil {
		return err
	}

	query := `
		UPDATE public.data_service_requests 
		SET "Send_status" = $1, "Send_response" = $2, "Updated_at" = NOW()
		WHERE id = $3
	`

	_, err = pgDB.ExecContext(ctx, query, status, responsePayload, reqID)
	return err
}
