package patient

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

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

	data := e.Patient{}
	if err := setData(&input, &data); err != nil {
		return nil, err
	}

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

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

	tx = tx.Preload(clause.Associations)
	tx = tx.Preload("Person.BirthRegency.Province").
		Preload("Person.Ethnic").
		Preload("Person.Language").
		Preload("Person.Contacts").
		Preload("Person.Relatives.Village.District.Regency.Province").
		Preload("Person.Addresses.Village.District.Regency.Province").
		Preload("Person.Addresses.PostalRegion.Village.District.Regency.Province").
		Preload("Person.Insurances.InsuranceCompany").
		Preload("Person.VclaimMember")

	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.Patient, event *pl.Event, dbx ...*gorm.DB) error {
	pl.SetLogInfo(event, data, "started", "DBUpdate")
	if err := setData(&input, data); err != nil {
		return err
	}

	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.Patient, 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
}

// Search By Resident Identity Number
func SearchDataByRIN(input e.SearchDto, event *pl.Event, dbx ...*gorm.DB) (*e.Patient, error) {
	pl.SetLogInfo(event, input, "started", "DBSearch")

	var data e.Patient

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

	// Preload associations for complete data
	tx = tx.Preload(clause.Associations)
	tx = tx.Preload("Person.Addresses").
		Preload("Person.Contacts").
		Preload("Person.Relatives").
		Preload("Person.Insurances")

	// Search by patient person's resident identity number (exact match)
	err := tx.Joins("JOIN \"Person\" ON \"Patient\".\"Person_Id\" = \"Person\".\"Id\"").
		Where("\"Person\".\"ResidentIdentityNumber\" = ?",
			input.Search).
		First(&data).Error

	if err != nil {
		if processedErr := pu.HandleSearchError(err, event, source, input.Search, data); processedErr != nil {
			return nil, processedErr
		}
	}

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

func SearchData(input e.SearchDto, event *pl.Event, dbx ...*gorm.DB) ([]e.Patient, *e.MetaDto, error) {
	pl.SetLogInfo(event, input, "started", "DBSearch")

	var data []e.Patient
	pagination := gh.Pagination{}
	count := int64(0)
	meta := e.MetaDto{}

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

	// Preload associations for complete data
	tx = tx.Preload(clause.Associations)
	tx = tx.Preload("Person.Addresses").
		Preload("Person.Contacts").
		Preload("Person.Relatives").
		Preload("Person.Insurances")

	// Search by patient number OR person's resident identity number (exact match) OR person's name (partial match)
	tx = tx.Joins("JOIN \"Person\" ON \"Patient\".\"Person_Id\" = \"Person\".\"Id\"").
		Where("\"Patient\".\"Number\" ILIKE ? OR \"Person\".\"ResidentIdentityNumber\" ILIKE ? OR \"Person\".\"Name\" ILIKE ?",
			"%"+input.Search+"%", "%"+input.Search+"%", "%"+input.Search+"%")
	err := tx.Scopes(gh.Paginate(input, &pagination)).Find(&data).Error

	if err != nil {
		if processedErr := pu.HandleSearchError(err, event, source, input.Search, data); processedErr != nil {
			return nil, nil, processedErr
		}
	}

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

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