package com.astalange.web.controller;

import com.astalange.core.entity.AppUser;
import com.astalange.core.repository.AppUserRepository;
import com.astalange.core.security.CustomUserDetails;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class ChangePasswordController {

    private final AppUserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    public ChangePasswordController(AppUserRepository userRepository, PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }

    @GetMapping("/change-password")
    public String showChangePasswordForm() {
        return "change-password";
    }

    @PostMapping("/change-password")
    public String changePassword(
            @RequestParam String newPassword,
            @RequestParam String confirmPassword,
            Model model) {

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null || !(auth.getPrincipal() instanceof CustomUserDetails)) {
            return "redirect:/login";
        }

        CustomUserDetails userDetails = (CustomUserDetails) auth.getPrincipal();

        if (!newPassword.equals(confirmPassword)) {
            model.addAttribute("error", "Les mots de passe ne correspondent pas.");
            return "change-password";
        }

        if (newPassword.equals("AsTalange123")) {
            model.addAttribute("error", "Le nouveau mot de passe doit être différent de AsTalange123.");
            return "change-password";
        }

        if (newPassword.length() < 6) {
            model.addAttribute("error", "Le mot de passe doit contenir au moins 6 caractères.");
            return "change-password";
        }

        AppUser appUser = userRepository.findById(userDetails.getId())
                .orElseThrow(() -> new IllegalStateException("Utilisateur non trouvé"));

        appUser.setPassword(passwordEncoder.encode(newPassword));
        appUser.setMustChangePassword(false);
        userRepository.save(appUser);

        // Update Authentication in Security Context
        CustomUserDetails newPrincipal = new CustomUserDetails(
                appUser.getId(),
                appUser.getUsername(),
                appUser.getPassword(),
                appUser.isEnabled(),
                false,
                auth.getAuthorities()
        );
        UsernamePasswordAuthenticationToken newAuth = new UsernamePasswordAuthenticationToken(
                newPrincipal, auth.getCredentials(), auth.getAuthorities()
        );
        SecurityContextHolder.getContext().setAuthentication(newAuth);

        return "redirect:/?passwordChanged=true";
    }
}
