package de.assecutor.votianlt.pages.service;

import de.assecutor.votianlt.model.User;
import de.assecutor.votianlt.repository.UserRepository;
import org.bson.types.ObjectId;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class UserService {

    private final PasswordEncoder passwordEncoder;
    private final UserRepository userRepository;

    public UserService(PasswordEncoder passwordEncoder, UserRepository userRepository) {
        this.passwordEncoder = passwordEncoder;
        this.userRepository = userRepository;
    }

    public User findByEmail(String email) {
        return userRepository.findByEmail(email).orElse(null);
    }

    public User findById(ObjectId id) {
        return userRepository.findById(id).orElse(null);
    }

    public User save(User user) {
        if (user.getPassword() != null && !user.getPassword().startsWith("$2a$")) {
            // Passwort verschlüsseln, falls noch nicht verschlüsselt
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }

        // Timestamps setzen
        if (user.getCreatedAt() == null) {
            user.setCreatedAt(LocalDateTime.now());
        }
        user.setUpdatedAt(LocalDateTime.now());

        return userRepository.save(user);
    }

    public boolean existsByEmail(String email) {
        return userRepository.existsByEmail(email);
    }

    public User createUser(String email, String password, String firstName, String lastName) {
        if (existsByEmail(email)) {
            throw new RuntimeException("User with email " + email + " already exists");
        }

        User user = new User();
        user.setEmail(email);
        user.setPassword(password); // wird in save() verschlüsselt
        user.setFirstname(firstName);
        user.setName(lastName);
        user.setIsActivated((byte) 1);
        user.setIsEmailConfirmed((byte) 1);

        return save(user);
    }
}
