package person

import (
	"errors"
	"strconv"

	e "simrs-vx/internal/domain/main-entities/person"

	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"
	d "github.com/karincake/dodol"
	gh "github.com/karincake/getuk"
	"gorm.io/gorm"
)

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

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

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

	tx = tx.Preload("Contacts").
		Preload("Addresses")

	if input.ResidentIdentityNumber != nil {
		tx = tx.Where("\"ResidentIdentityNumber\" = ?", *input.ResidentIdentityNumber)
	}

	if input.PassportNumber != nil {
		tx = tx.Where("\"PassportNumber\" = ?", *input.PassportNumber)
	}
	if input.DrivingLicenseNumber != nil {
		tx = tx.Where("\"DrivingLicenseNumber\" = ?", *input.DrivingLicenseNumber)
	}
	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.Person, 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.Person, 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 CreateOrUpdatePerson(input *e.UpdateDto, event *pl.Event, tx *gorm.DB) (*uint, error) {
	inputCreateData := input.CreateDto
	if input.Id == 0 {
		person, err := CreateData(input.CreateDto, event, tx)
		if err != nil {
			return nil, err
		}

		return &person.Id, nil
	}

	person, err := ReadDetailData(e.ReadDetailDto{Id: input.Id}, event, tx)
	if err != nil {
		return nil, err
	}

	if person == nil {
		event.Status = "failed"
		event.ErrInfo = pl.ErrorInfo{
			Code:   "data-notFound",
			Detail: "person with ID " + strconv.Itoa(int(input.Id)) + " not found",
			Raw:    errors.New("person with ID " + strconv.Itoa(int(input.Id)) + " not found"),
		}
		return nil, pl.SetLogError(event, input)
	}

	if person.IsSameResidentIdentityNumber(input.ResidentIdentityNumber) {
		if err := UpdateData(e.UpdateDto{CreateDto: input.CreateDto}, person, event, tx); err != nil {
			return nil, err
		}
		return &person.Id, nil
	}

	dup, err := ReadDetailData(e.ReadDetailDto{ResidentIdentityNumber: input.ResidentIdentityNumber}, event, tx)
	if err != nil {
		if fieldErr, ok := err.(d.FieldError); ok && fieldErr.Code == "data-notFound" {
		} else {
			return nil, err
		}
	} else if dup != nil && dup.Id != person.Id {
		event.Status = "failed"
		event.ErrInfo = pl.ErrorInfo{
			Code:   "data-duplicate",
			Detail: "person with ResidentIdentityNumber " + *input.ResidentIdentityNumber + " already exists",
			Raw:    errors.New("person with ResidentIdentityNumber " + *input.ResidentIdentityNumber + " already exists"),
		}
		return nil, pl.SetLogError(event, input)
	}

	if err := UpdateData(e.UpdateDto{CreateDto: inputCreateData}, person, event, tx); err != nil {
		return nil, err
	}

	return &person.Id, nil
}
