package dev_services

import (
	"cpone/db"
	"cpone/models"
	dbx "cpone/package/database"
	"fmt"
	"math"

	"go.uber.org/zap"
)

type McuDaftarPesertaServices struct {
	McuDaftarPesertaStore db.AppStore
}

func NewMcuDaftarPesertaServices(uStore db.AppStore) *McuDaftarPesertaServices {
	return &McuDaftarPesertaServices{
		McuDaftarPesertaStore: uStore,
	}
}

func (mdp *McuDaftarPesertaServices) GetListMcuDaftarPeserta(id string, currentPage int, rowPerPage int) ([]models.ModelMcuDaftarPeserta, int, error) {
	logger, _ := zap.NewProduction()
	var listDaftarPeserta []models.ModelMcuDaftarPeserta
	var totalData int
	offset := (currentPage - 1) * rowPerPage

	querytotal := `SELECT COUNT(*)
		FROM t_orderheader
		JOIN m_patient ON T_OrderHeaderM_PatientID = M_PatientID
		AND M_PatientIsActive = 'Y'
		WHERE T_OrderHeaderIsActive = 'Y' AND T_OrderHeaderMgm_McuID = ?`

	if err := dbx.Handlex.Get(&totalData, querytotal, id); err != nil {
		return nil, 0, fmt.Errorf("error querying database: %v", err)
	}

	query := `SELECT T_OrderHeaderID,
		T_OrderHeaderDate,
		T_OrderHeaderLabNumber,
		T_OrderHeaderM_PatientAge,
		M_PatientID,
		M_PatientNoReg,
		M_PatientName,
		M_PatientGender,
		CASE 
		WHEN M_PatientGender = 'male' THEN 'Laki - Laki'
		WHEN M_PatientGender = 'female' THEN 'Perempuan'
		ELSE ' '
		END AS jenisKelamin,
		M_PatientDOB,
		FLOOR(DATEDIFF(CURDATE(), M_PatientDOB)/ 365.25) AS age
		FROM t_orderheader
		JOIN m_patient ON T_OrderHeaderM_PatientID = M_PatientID
		AND M_PatientIsActive = 'Y'
		WHERE T_OrderHeaderIsActive = 'Y' AND T_OrderHeaderMgm_McuID = ?
		ORDER BY M_PatientName ASC
		LIMIT ? OFFSET ?`

	if err := dbx.Handlex.Select(&listDaftarPeserta, query, id, rowPerPage, offset); err != nil {
		return nil, 0, fmt.Errorf("error querying database: %v", err)
	}
	totalPage := int(math.Ceil(float64(totalData) / float64(rowPerPage)))

	defer logger.Sync()
	logger.Info("GET DATA PESERTA",
		zap.Any("id", id),
		zap.Any("total data", totalData),
		zap.Any("peserta", listDaftarPeserta),
	)

	return listDaftarPeserta, totalPage, nil
}
