package employee

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

	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"
	"gorm.io/gorm/clause"
)

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

	data := e.Employee{}
	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.Employee, *e.MetaDto, error) {
	pl.SetLogInfo(event, input, "started", "DBReadList")
	data := []e.Employee{}
	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.Employee{}).
		Scopes(gh.Preload(input.Includes)).
		Scopes(gh.Filter(input.FilterDto)).
		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, plh.HandleListError(input, event, err)
	}

	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.Employee, error) {
	pl.SetLogInfo(event, input, "started", "DBReadDetail")
	data := e.Employee{}

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

	tx = tx.Preload(clause.Associations)
	tx = tx.Preload("Person.Addresses")
	tx = tx.Preload("Person.Contacts")
	tx = tx.Preload("Person.Relatives")

	if input.User_Id != nil {
		tx = tx.Where("\"User_Id\" = ?", *input.User_Id)
	}
	if input.Person_Id != nil {
		tx = tx.Where("\"Person_Id\" = ?", *input.Person_Id)
	}
	if input.Number != nil {
		tx = tx.Where("\"Number\" = ?", *input.Number)
	}
	if input.Id != 0 {
		tx = tx.Where("\"Id\" = ?", input.Id)
	}

	if err := tx.First(&data).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.Employee, 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.Employee, 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 CreateOrUpdate(input e.UpdateDto, event *pl.Event, dbx ...*gorm.DB) (*e.Employee, error) {
	pl.SetLogInfo(event, nil, "started", "DBCreateOrUpdate")

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

	data := e.Employee{}

	if input.Id > 0 {
		if err := tx.Where("\"Id\" = ? AND \"User_Id\" = ?", input.Id, input.User_Id).First(&data).Error; err == nil {
			setData(&input, &data)
			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 nil, pl.SetLogError(event, input)
			}
			return &data, nil
		} else if err != gorm.ErrRecordNotFound {
			event.Status = "failed"
			event.ErrInfo = pl.ErrorInfo{
				Code:   "data-get-fail",
				Detail: "Database get failed",
				Raw:    err,
			}
			return nil, pl.SetLogError(event, input)
		}
		return nil, nil
	}

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

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