package crud

import (
	e "simrs-vx/internal/domain/_template/single"

	dg "github.com/karincake/apem/db-gorm-pg"
	gh "github.com/karincake/getuk"
	"gorm.io/gorm"
)

func CreateData(input *e.Single, dbx ...*gorm.DB) (*e.Single, error) {
	var tx *gorm.DB
	if len(dbx) > 0 {
		tx = dbx[0]
	} else {
		tx = dg.I
	}

	if err := tx.Create(&input).Error; err != nil {
		return nil, err
	}

	return &data, err
}

func ReadListData(input e.ReadListDto, dbx ...*gorm.DB) ([]e.Single, *e.MetaDto, error) {
	data := []e.Single{}
	pagination := gh.Pagination{}
	count := int64(0)
	meta := e.MetaDto{}

	var tx *gorm.DB
	if len(dbx) > 0 {
		tx = dbx[0]
	} else {
		tx = dg.I
	}

	tx = tx.
		Model(&e.Single{}).
		// Joins("Patient"). // if needed
		// Preload("Patient"). // if needed
		Scopes(gh.Filter(input)).
		Count(&count).
		Scopes(gh.Paginate(input, &pagination)).
		Order("CreatedAt DESC")

	if err := tx.Find(&data).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, &meta, nil
		}
		return nil, nil, err

	}
	meta.Count = count
	meta.PageNumber = pagination.PageNumber
	meta.PageSize = pagination.PageSize
	return data, &meta, nil
}

func ReadDetailData(input e.ReadDetailDto, dbx ...*gorm.DB) (*e.Single, error) {
	data := e.Single{}

	var tx *gorm.DB
	if len(dbx) > 0 {
		tx = dbx[0]
	} else {
		tx = dg.I
	}

	if err := tx.First(&data, input.Id).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		return nil, err
	}

	return &data, nil
}

func UpdateData(input e.Single, dbx ...*gorm.DB) error {
	var tx *gorm.DB
	if len(dbx) > 0 {
		tx = dbx[0]
	} else {
		tx = dg.I
	}

	return tx.Save(&input).Error
}

func DeleteData(input *e.Single, dbx ...*gorm.DB) error {
	var tx *gorm.DB
	if len(dbx) > 0 {
		tx = dbx[0]
	} else {
		tx = dg.I
	}

	return tx.Delete(input).Error
}
