package mysqlbenefactor

import (
	"database/sql"
	"time"

	"git.gocasts.ir/ebhomengo/niki/entity"
	"git.gocasts.ir/ebhomengo/niki/repository/mysql"
)

func scanBenefactor(scanner mysql.Scanner) (entity.Benefactor, error) {
	var createdAt, updatedAt time.Time
	var benefactor entity.Benefactor
	// TODO - use db model and mapper between entity and db model OR use this approach

	var benefactorNullableFields nullableFields

	err := scanner.Scan(&benefactor.ID, &benefactorNullableFields.firstName,
		&benefactorNullableFields.lastName, &benefactor.PhoneNumber, &benefactorNullableFields.description,
		&benefactorNullableFields.email, &benefactorNullableFields.genderStr,
		&benefactorNullableFields.birthdate, &createdAt, &updatedAt, &benefactor.Status)

	mapNotNullToBenefactor(benefactorNullableFields, &benefactor)

	return benefactor, err
}

type nullableFields struct {
	firstName   sql.NullString
	lastName    sql.NullString
	description sql.NullString
	email       sql.NullString
	genderStr   sql.NullString
	birthdate   sql.NullTime
}

// TODO - find the other solution.
func mapNotNullToBenefactor(data nullableFields, benefactor *entity.Benefactor) {
	if data.firstName.Valid {
		benefactor.FirstName = data.firstName.String
	}
	if data.lastName.Valid {
		benefactor.LastName = data.lastName.String
	}

	if data.description.Valid {
		benefactor.Description = data.description.String
	}
	if data.email.Valid {
		benefactor.Email = data.email.String
	}

	if data.genderStr.Valid {
		benefactor.Gender = entity.Gender(data.genderStr.String)
	}
	if data.birthdate.Valid {
		benefactor.BirthDate = data.birthdate.Time
	}
}
