package validation

import (
	"GoMembership/internal/constants"
	"GoMembership/internal/models"
	"GoMembership/internal/repositories"
	"GoMembership/pkg/logger"
	"time"

	"github.com/go-playground/validator/v10"
)

func validateUser(sl validator.StructLevel) {
	user := sl.Current().Interface().(models.User)

	isSuper := user.RoleID >= constants.Roles.Admin

	if user.RoleID > constants.Roles.Member && user.Password == "" {
		passwordExists, err := repositories.PasswordExists(&user.ID)
		if err != nil || !passwordExists {
			logger.Error.Printf("Error checking password exists for user %v: %v", user.Email, err)
			sl.ReportError(user.Password, "Password", "password", "required", "")
		}
	}
	// Validate User > 18 years old
	if !isSuper && user.DateOfBirth.After(time.Now().AddDate(-18, 0, 0)) {
		sl.ReportError(user.DateOfBirth, "DateOfBirth", "dateofbirth", "age", "")
	}
	// validate subscriptionModel
	if user.Membership.SubscriptionModel.Name == "" {
		sl.ReportError(user.Membership.SubscriptionModel.Name, "SubscriptionModel.Name", "name", "required", "")
	} else {
		selectedModel, err := repositories.GetSubscriptionByName(&user.Membership.SubscriptionModel.Name)
		if err != nil {
			logger.Error.Printf("Error finding subscription model for user %v: %v", user.Email, err)
			sl.ReportError(user.Membership.SubscriptionModel.Name, "SubscriptionModel.Name", "name", "invalid", "")
		} else {
			user.Membership.SubscriptionModel = *selectedModel
		}
	}

	validateMembership(sl)
	if !isSuper {
		validateBankAccount(sl)
		if user.Licence != nil {
			validateDriverslicence(sl)
		}
	}
}
