package doctor

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

	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.Doctor, error) {
	pl.SetLogInfo(event, nil, "started", "DBCreate")

	data := e.Doctor{}
	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.Doctor, *e.MetaDto, error) {
	pl.SetLogInfo(event, input, "started", "DBReadList")
	data := []e.Doctor{}
	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.Doctor{}).
		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.Doctor, error) {
	pl.SetLogInfo(event, input, "started", "DBReadDetail")
	data := e.Doctor{}

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

	if input.Employee_Id != nil {
		tx = tx.Where("\"Employee_Id\" = ?", *input.Employee_Id)
	}
	if input.Id != nil {
		tx = tx.Where("\"Id\" = ?", input.Id)
	}
	if input.Code != nil {
		tx = tx.Where("\"Code\" = ?", input.Code)
	}
	fmt.Println(input.Includes)
	if err := tx.Scopes(gh.Preload(input.Includes)).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.Doctor, 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.Doctor, 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 GetIdByUserId(user_id *uint, event *pl.Event, dbx ...*gorm.DB) (*uint, error) {
	pl.SetLogInfo(event, nil, "started", "DBGetIdByUserId")
	var tx *gorm.DB
	if len(dbx) > 0 {
		tx = dbx[0]
	} else {
		tx = dg.I
	}

	var doctor_id uint

	err := tx.Model(&e.Doctor{}).
		Select("\"Doctor\".\"Id\" as doctor_id").
		Joins("JOIN \"Employee\" as e ON e.\"Id\" = \"Doctor\".\"Employee_Id\"").
		Where("e.\"User_Id\" = ?", user_id).
		Scan(&doctor_id).Error

	if err != nil {
		event.Status = "failed"
		event.ErrInfo = pl.ErrorInfo{
			Code:   "data-get-fail",
			Detail: "Database get failed",
			Raw:    err,
		}
		return nil, pl.SetLogError(event, user_id)
	}

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