package com.example.dateplanner.configurations;

import com.example.dateplanner.models.entities.AppUser;
import com.example.dateplanner.models.enums.Role;
import com.example.dateplanner.repositories.AppUserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;
import reactor.core.publisher.Mono;

@Slf4j
@Configuration
public class AppConfig {

    private final String username = "morgan";
    private final String password = "Admin_123!";

    @Bean
    public CommandLineRunner prepare(AppUserRepository userRepository, PasswordEncoder encoder) {
        return args -> {
            log.info("***************** environments start *******************");
            for (String key : System.getenv().keySet()) {
                String[] p = key.split("\\.");
                if (p.length > 1) {
                    log.info("\"{}\"=\"{}\"", key, System.getenv().get(key));
                }
            }
            log.info("****************** environments end ********************");
            userRepository.findByPhone(username).flatMap(existingUser -> {
                log.info("User {} exist.", existingUser.getPhone());
                return Mono.just(existingUser);
            }).switchIfEmpty(
                    Mono.defer(() -> {
                        log.info("User not found! Create default admin user: {}, password: {}", username,password);
                        AppUser user = new AppUser();
                        user.setPhone(username);
                        user.setPassword(encoder.encode(password));
                        user.setLastName("Admin");
                        user.setFirstName("Master");
                        user.setRole(Role.ADMIN);
                        return userRepository.save(user);
                    })
            ).flatMap(u -> {
                log.info("User in db: [{}]", u);
                return Mono.empty();
            }).subscribe();
        };
    }
}
