package personaddress

import (
	e "simrs-vx/internal/domain/main-entities/person-address"

	plh "simrs-vx/pkg/lib-helper"
	pl "simrs-vx/pkg/logger"
	pu "simrs-vx/pkg/use-case-helper"

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

func CreateData(input e.CreateDto, event *pl.Event, dbx ...*gorm.DB) (*e.PersonAddress, error) {
	pl.SetLogInfo(event, nil, "started", "DBCreate")

	data := e.PersonAddress{}
	setData(&input, &data)

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

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

	pl.SetLogInfo(event, nil, "complete")
	return &data, nil
}

func ReadListData(input e.ReadListDto, event *pl.Event, dbx ...*gorm.DB) ([]e.PersonAddress, *e.MetaDto, error) {
	pl.SetLogInfo(event, input, "started", "DBReadList")
	data := []e.PersonAddress{}
	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.PersonAddress{}).
		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
		}
		event.Status = "failed"
		event.ErrInfo = pl.ErrorInfo{
			Code:   "data-get-fail",
			Detail: "Database get failed",
			Raw:    err,
		}
		return nil, nil, pl.SetLogError(event, input)

	}
	meta.Count = int(count)
	meta.PageNumber = pagination.PageNumber
	meta.PageSize = pagination.PageSize

	pl.SetLogInfo(event, nil, "complete")
	return data, &meta, nil
}

func ReadDetailData(input e.ReadDetailDto, event *pl.Event, dbx ...*gorm.DB) (*e.PersonAddress, error) {
	pl.SetLogInfo(event, input, "started", "DBReadDetail")
	data := e.PersonAddress{}

	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 processedErr := pu.HandleReadError(err, event, source, input.Id, data); processedErr != nil {
			return nil, processedErr
		}
	}

	pl.SetLogInfo(event, nil, "complete")
	return &data, nil
}

func UpdateData(input e.UpdateDto, data *e.PersonAddress, event *pl.Event, dbx ...*gorm.DB) error {
	pl.SetLogInfo(event, data, "started", "DBUpdate")
	setData(&input, data)

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

	if err := tx.Save(&data).Error; err != nil {
		event.Status = "failed"
		event.ErrInfo = pl.ErrorInfo{
			Code:   "data-update-fail",
			Detail: "Database update failed",
			Raw:    err,
		}
		return pl.SetLogError(event, input)
	}

	pl.SetLogInfo(event, nil, "complete")
	return nil
}

func DeleteData(data *e.PersonAddress, event *pl.Event, dbx ...*gorm.DB) error {
	pl.SetLogInfo(event, data, "started", "DBDelete")
	var tx *gorm.DB
	if len(dbx) > 0 {
		tx = dbx[0]
	} else {
		tx = dg.I
	}

	if err := tx.Delete(&data).Error; err != nil {
		event.Status = "failed"
		event.ErrInfo = pl.ErrorInfo{
			Code:   "data-delete-fail",
			Detail: "Database delete failed",
			Raw:    err,
		}
		return pl.SetLogError(event, data)
	}

	pl.SetLogInfo(event, nil, "complete")
	return nil
}

func CreateOrUpdateBatch(input []e.UpdateDto, event *pl.Event, tx ...*gorm.DB) error {
	var data = make([]e.PersonAddress, len(input))
	var dbx *gorm.DB
	if len(tx) > 0 {
		dbx = tx[0]
	} else {
		dbx = dg.I
	}

	for idx := range input {
		if input[idx].Id > 0 {
			if err := dbx.Where("\"Id\" = ? AND \"Person_Id\" = ?", input[idx].Id, input[idx].Person_Id).First(&data[idx]).Error; err == nil {
				setData(&input[idx], &data[idx])
				if err := dbx.Save(&data[idx]).Error; err != nil {
					event.Status = "failed"
					event.ErrInfo = pl.ErrorInfo{
						Code:   "data-update-fail",
						Detail: "Database update failed",
						Raw:    err,
					}
					return pl.SetLogError(event, input)
				}
			} else if err != gorm.ErrRecordNotFound {
				event.Status = "failed"
				event.ErrInfo = pl.ErrorInfo{
					Code:   "data-get-fail",
					Detail: "Database get failed",
					Raw:    err,
				}
				return pl.SetLogError(event, input)
			}
			continue
		}
		setData(&input[idx], &data[idx])
		if err := dbx.Create(&data[idx]).Error; err != nil {
			event.Status = "failed"
			event.ErrInfo = pl.ErrorInfo{
				Code:   "data-create-fail",
				Detail: "Database insert failed",
				Raw:    err,
			}
			return pl.SetLogError(event, input)
		}
	}

	return nil
}

func DeleteMultipleData(personId *uint, event *pl.Event, dbx ...*gorm.DB) error {
	pl.SetLogInfo(event, personId, "started", "DBDelete")
	var tx *gorm.DB
	if len(dbx) > 0 {
		tx = dbx[0]
	} else {
		tx = dg.I
	}

	if err := tx.
		Where("\"Person_Id\" = ?", *personId).
		Delete(&e.PersonAddress{}).Error; err != nil {
		event.Status = "failed"
		event.ErrInfo = pl.ErrorInfo{
			Code:   "data-delete-fail",
			Detail: "Database delete failed",
			Raw:    err,
		}
		return pl.SetLogError(event, personId)
	}

	pl.SetLogInfo(event, nil, "complete")
	return nil
}
