package user

import (
	"Yimaru-Backend/internal/domain"
	"context"
	"time"
)

func (s *Service) UpdateUserKnowledgeLevel(ctx context.Context, userID int64, knowledgeLevel string) error {
	return s.userStore.UpdateUserKnowledgeLevel(ctx, userID, knowledgeLevel)
}

func (s *Service) CreateUser(
	ctx context.Context,
	req domain.CreateUserReq,
	isCompany bool,
) (domain.User, error) {

	// Hash the password
	hashedPassword, err := hashPassword(req.Password)
	if err != nil {
		return domain.User{}, err
	}

	// Create the user
	return s.userStore.CreateUserWithoutOtp(ctx, domain.User{
		FirstName: req.FirstName,
		LastName:  req.LastName,
		// UserName:         req.UserName,
		Email:            req.Email,
		PhoneNumber:      req.PhoneNumber,
		Password:         hashedPassword,
		Role:             domain.Role(req.Role),
		EmailVerified:    true, // assuming auto-verified on creation
		PhoneVerified:    true,
		Status:           domain.UserStatusActive,
		AgeGroup:         req.AgeGroup,
		EducationLevel:   req.EducationLevel,
		Country:          req.Country,
		Region:           req.Region,
		ProfileCompleted: false,
	})
}

func (s *Service) DeleteUser(ctx context.Context, id int64) error {
	// Delete User
	return s.userStore.DeleteUser(ctx, id)
}

func (s *Service) GetAllUsers(
	ctx context.Context,
	filter domain.UserFilter,
) ([]domain.User, int64, error) {

	var before *time.Time
	if filter.CreatedBefore.Valid {
		before = &filter.CreatedBefore.Value
	}

	var after *time.Time
	if filter.CreatedAfter.Valid {
		after = &filter.CreatedAfter.Value
	}

	var role *string
	if filter.Role != "" {
		role = &filter.Role
	}

	var query *string
	if filter.Query != "" {
		query = &filter.Query
	}

	offset := int32(filter.Page * filter.PageSize)

	return s.userStore.GetAllUsers(
		ctx,
		role,
		query,
		before,
		after,
		int32(filter.PageSize),
		offset,
	)
}

func (s *Service) GetUserById(ctx context.Context, id int64) (domain.User, error) {

	return s.userStore.GetUserByID(ctx, id)
}
