package validation

import (
	"time"

	"bitbucket.org/nemt/nemt-portal-api/application/viewmodel"
	"bitbucket.org/nemt/nemt-portal-api/infra/errors"
)

func ValidateVisit(visit *viewmodel.Visit, user *viewmodel.User) []errors.ValidationError {
	var result []errors.ValidationError
	// Step #1
	if len(visit.Provider.ProviderUUID) == 0 {
		result = append(result, errors.ValidationError{Field: "provider.id", Message: "Step #1 - Provider is required"})
	}

	// Step #2
	eligibilityResult := ValidateEligibility(&visit.User)
	if len(eligibilityResult) > 0 {
		result = append(result, eligibilityResult...)
	}

	//Step #3
	if visit.VisitDatetime.IsZero() {
		result = append(result, errors.ValidationError{Field: "visit_datetime", Message: "Step #3 - Choose a Date for the Visit"})
	} else {
		isVisitDayToday := visit.VisitDatetime.Day() == time.Now().Day() && visit.VisitDatetime.Month() == time.Now().Month() && visit.VisitDatetime.Year() == time.Now().Year()
		before8Hours := time.Now().Add(-time.Hour * time8Hours)
		dayBeforeToday := time.Now().Add(-time.Hour * hoursInDay)
		if visit.VisitDatetime.Before(dayBeforeToday) {
			result = append(result, errors.ValidationError{Field: "visit_datetime", Message: "Step #3 - Visit cannot occur more than one day before today"})
		}

		dayAfter180Days := time.Now().Add(time.Hour * hoursIn180Days)
		if visit.VisitDatetime.After(dayAfter180Days) {
			result = append(result, errors.ValidationError{Field: "visit_datetime", Message: "Step #3 - Visit cannot occur more than 180 days after today"})
		}

		if isVisitDayToday && visit.VisitDatetime.Before(before8Hours) {
			result = append(result, errors.ValidationError{Field: "visit_datetime", Message: "Step #3 - Visit is more than 8 hours in the past"})
		}
	}

	return result
}
