package de.assecutor.votianlt.config;

import de.assecutor.votianlt.model.User;
import de.assecutor.votianlt.repository.UserRepository;
import de.assecutor.votianlt.service.DemoModeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Set;

@Component
public class DataInitializer implements CommandLineRunner {

    private static final Logger log = LoggerFactory.getLogger(DataInitializer.class);

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    private final DemoModeService demoModeService;

    public DataInitializer(UserRepository userRepository, PasswordEncoder passwordEncoder,
            DemoModeService demoModeService) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
        this.demoModeService = demoModeService;
    }

    @Override
    public void run(String... args) throws Exception {
        initializeTestUsers();
        demoModeService.ensureDemoUser();
    }

    private void initializeTestUsers() {
        log.info("Initializing test users...");

        // Admin User
        if (!userRepository.existsByEmail("admin@votianlt.de")) {
            User adminUser = new User();
            adminUser.setEmail("admin@votianlt.de");
            adminUser.setPassword(passwordEncoder.encode("admin123"));
            adminUser.setName("Administrator");
            adminUser.setFirstname("Admin");
            adminUser.setIsActivated((byte) 1);
            adminUser.setIsEmailConfirmed((byte) 1);
            adminUser.setCreatedAt(LocalDateTime.now());
            adminUser.setUpdatedAt(LocalDateTime.now());
            adminUser.setRoles(Set.of("USER", "ADMIN"));
            adminUser.setTwoFactorEnabled(false); // 2FA deaktiviert für Admin

            userRepository.save(adminUser);
            log.info("Created admin user: admin@votianlt.de / admin123 (2FA enabled)");
        } else {
            // Stelle sicher, dass bestehender Admin 2FA deaktiviert hat
            userRepository.findByEmail("admin@votianlt.de").ifPresent(adminUser -> {
                if (adminUser.isTwoFactorEnabled()) {
                    adminUser.setTwoFactorEnabled(false);
                    userRepository.save(adminUser);
                    log.info("Updated admin user: 2FA disabled");
                }
            });
        }

        log.info("Test users initialization completed.");
    }
}
